{
  "id": "sWkIlmUgJKHT6H6c",
  "name": "Assess an operating model and generate an AI transformation blueprint",
  "tags": [],
  "nodes": [
    {
      "id": "e05f308a-8c4d-44c5-b1b8-0e98191e5edd",
      "name": "Community Overview",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        100,
        500
      ],
      "parameters": {
        "width": 650,
        "height": 1850,
        "content": "## Assess an operating model and generate an AI transformation blueprint\n\n### Who\u2019s it for\n\nTransformation consultants, automation teams and operations leaders who need to turn operating-model evidence into an evidence-led AI transformation pack.\n\n### What this workflow does\n\n1. Collects organisational evidence from Google Drive and Google Sheets.\n2. Normalises RACI, tool inventory, KPIs and user-provided benchmark data.\n3. Uses OpenAI to identify inefficiencies and map AI/automation opportunities.\n4. Generates a target operating model, future-state architecture and RACI.\n5. Models cautious, hybrid and aggressive financial scenarios.\n6. Assesses change readiness using ADKAR values supplied in the configuration node.\n7. Generates Mermaid diagrams, an executive transformation report and structured outputs.\n8. Writes results to Google Sheets and uploads the report to Google Drive.\n9. Includes optional Slack, Gmail, queue and Supabase modules.\n\n### Set up before first run\n\n- [ ] Open `Set Client Config`.\n- [ ] Enter your Google Drive source file ID.\n- [ ] Enter your master Google Sheet ID.\n- [ ] Enter your output Google Drive folder ID.\n- [ ] Review the financial assumptions.\n- [ ] Review the ADKAR scores and stakeholder JSON.\n- [ ] Select Google Drive credentials.\n- [ ] Select Google Sheets credentials.\n- [ ] Select OpenAI credentials.\n- [ ] Create the required Google Sheet tabs listed in the README.\n- [ ] Leave optional Slack, Gmail, queue and Supabase modules disabled until configured.\n\n### Important controls\n\n- Quantitative benchmarks are **not embedded**. Add your own evidence to the `Benchmarks` tab.\n- Financial assumptions are visible configuration inputs, not universal facts.\n- Change-readiness scores are user inputs, not fabricated by the workflow.\n- AI outputs should be reviewed before being presented as client recommendations.\n\n### Requirements\n\nn8n, OpenAI, Google Drive and Google Sheets. Slack, Gmail and Supabase are optional.\n\n### Customise\n\nChange input tabs, scoring logic, model prompts, financial assumptions, report format, notification channels or memory layer to fit your operating model."
      },
      "typeVersion": 1
    },
    {
      "id": "70ee8869-e329-4b5a-b205-069e947efdfe",
      "name": "Community Section 1",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        900,
        500
      ],
      "parameters": {
        "color": 7,
        "width": 1400,
        "height": 880,
        "content": "## Setup and trigger\n\nConfigure the assessment once, then run manually. An optional Google Sheets queue path is included as a disabled extension for teams that want repeatable multi-client intake."
      },
      "typeVersion": 1
    },
    {
      "id": "289621e9-9a6d-4cd3-9f47-e4dc3a5d504a",
      "name": "Community Section 2",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        2600,
        500
      ],
      "parameters": {
        "color": 7,
        "width": 1400,
        "height": 1130,
        "content": "## Collect operating-model evidence\n\nCollects organisational evidence from Google Drive and a master Google Sheet: RACI, tools inventory, KPI snapshot and user-supplied benchmarks. The cleaner normalises inputs and records data quality."
      },
      "typeVersion": 1
    },
    {
      "id": "7c5a32f2-b9a6-42ba-9ee7-29b8689d1d4b",
      "name": "Community Section 3",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        4300,
        500
      ],
      "parameters": {
        "color": 7,
        "width": 1400,
        "height": 880,
        "content": "## Analyse current state and opportunities\n\nUses OpenAI for qualitative inefficiency analysis and AI/automation fit mapping, then combines this with user-provided benchmark evidence. Recommendations should remain evidence-led and subject to human review."
      },
      "typeVersion": 1
    },
    {
      "id": "160fade9-0f59-4141-b176-fd0e54a26874",
      "name": "Community Section 4",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        900,
        2700
      ],
      "parameters": {
        "color": 7,
        "width": 2200,
        "height": 1130,
        "content": "## Design the future operating model\n\nBuilds the target operating model, financial scenarios, change-readiness view, RACI, diagrams, KPI projections and executive narrative. Financial and ADKAR assumptions come from the visible configuration node."
      },
      "typeVersion": 1
    },
    {
      "id": "7f51a530-b197-4308-87a7-0e080c913c71",
      "name": "Community Section 5",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        3400,
        2700
      ],
      "parameters": {
        "color": 7,
        "width": 2800,
        "height": 1130,
        "content": "## Package and persist deliverables\n\nCreates the report payload, writes structured outputs to Google Sheets and uploads the professional report to Google Drive. Disabled split/write nodes are retained where they support optional output tables."
      },
      "typeVersion": 1
    },
    {
      "id": "6f783daf-46ad-485a-b03a-a514267e89d4",
      "name": "Community Section 6",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        6500,
        2700
      ],
      "parameters": {
        "color": 7,
        "width": 1500,
        "height": 880,
        "content": "## Optional delivery and memory extensions\n\nOptional floating modules for email, Slack, queue completion and Supabase memory. Configure credentials and destinations, then enable only the modules you need."
      },
      "typeVersion": 1
    },
    {
      "id": "da6b33ce-369a-42fb-968f-55a3c9b4ceca",
      "name": "Manual Trigger - Start Audit",
      "type": "n8n-nodes-base.manualTrigger",
      "disabled": false,
      "position": [
        990,
        760
      ],
      "parameters": {},
      "typeVersion": 1
    },
    {
      "id": "f6f4584d-594b-4826-861a-0c11431ed40e",
      "name": "1.1 Google Drive - Org Data",
      "type": "n8n-nodes-base.googleDrive",
      "position": [
        2690,
        760
      ],
      "parameters": {
        "fileId": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $('Set Client Config').first().json.org_drive_file_id }}"
        },
        "options": {
          "googleFileConversion": {
            "conversion": {
              "docsToFormat": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
              "drawingsToFormat": "application/pdf"
            }
          }
        },
        "operation": "download"
      },
      "typeVersion": 3
    },
    {
      "id": "d272a164-74a2-444f-997f-dfb9e4dd536c",
      "name": "1.2 Google Sheets - RACI Matrix",
      "type": "n8n-nodes-base.googleSheets",
      "position": [
        3000,
        760
      ],
      "parameters": {
        "options": {},
        "sheetName": {
          "__rl": true,
          "mode": "name",
          "value": "RACI_Matrix"
        },
        "documentId": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $('Set Client Config').first().json.master_sheet_id }}"
        }
      },
      "typeVersion": 4.5
    },
    {
      "id": "31cd514d-736d-4bd3-ae38-adad92ba3c0a",
      "name": "1.4 KPI Snapshot - Google Sheets",
      "type": "n8n-nodes-base.googleSheets",
      "position": [
        2690,
        1010
      ],
      "parameters": {
        "options": {},
        "sheetName": {
          "__rl": true,
          "mode": "name",
          "value": "KPI_Snapshot"
        },
        "documentId": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $('Set Client Config').first().json.master_sheet_id }}"
        }
      },
      "typeVersion": 4.5
    },
    {
      "id": "458483f0-aff6-4ef9-b521-efeddec8fe6c",
      "name": "Merge Discovery Data",
      "type": "n8n-nodes-base.merge",
      "position": [
        3310,
        1010
      ],
      "parameters": {},
      "typeVersion": 3
    },
    {
      "id": "1f70a537-51ba-40f9-bdad-80a21baf6984",
      "name": "2.1 Data Cleaner",
      "type": "n8n-nodes-base.code",
      "position": [
        2690,
        1260
      ],
      "parameters": {
        "jsCode": "// Data Cleaner v5 - Enterprise Hardened Version\n// Google Sheets Compatible + Stable Client + Stable Audit ID\n\nconst items = $input.all();\n\n// ============================================================\n// HELPER FUNCTIONS\n// ============================================================\n\nfunction getField(obj, ...possibleNames) {\n  for (const name of possibleNames) {\n    if (obj[name] !== undefined) return obj[name];\n    const lower = name.toLowerCase();\n    for (const key of Object.keys(obj)) {\n      if (key.toLowerCase() === lower) return obj[key];\n    }\n  }\n  return null;\n}\n\nfunction safeGetNode(nodeName) {\n  try {\n    const node = $(nodeName);\n    if (node && node.first) return node.first().json;\n  } catch {}\n  return null;\n}\n\nfunction safeNumber(val, fallback = 0) {\n  const n = parseFloat(val);\n  return isNaN(n) ? fallback : n;\n}\n\n// ============================================================\n// SAFE CLIENT + AUDIT RESOLUTION\n// ============================================================\n\nconst dynamicCfg = safeGetNode('Optional - Map Queue Row to Config') || {};\nconst clientConfig = safeGetNode('Set Client Config') || {};\nconst baseInput = $input.first()?.json || {};\n\nconst resolvedClient =\n  clientConfig.client_name ||\n  dynamicCfg.client_name ||\n  baseInput.client_name ||\n  baseInput.Client_Name ||\n  \"Unknown Client\";\n\nconst resolvedAuditId =\n  clientConfig.audit_id ||\n  dynamicCfg.audit_id ||\n  baseInput.audit_id ||\n  baseInput.Audit_ID ||\n  null; // Only generate if truly missing\n\nconst auditIdFinal = resolvedAuditId || `AUDIT_${Date.now()}`;\nconst auditTimestamp =\n  clientConfig.audit_timestamp ||\n  dynamicCfg.audit_timestamp ||\n  new Date().toISOString();\n\n// ============================================================\n// INITIAL STRUCTURE\n// ============================================================\n\nconst currentModelData = {\n  client_name: resolvedClient,\n  audit_id: auditIdFinal,\n  audit_timestamp: auditTimestamp,\n  org_structure: [],\n  tools: [],\n  processes: [],\n  kpis: {},\n  raw_documents: [],\n  data_quality: 0\n};\n\nlet raciCount = 0;\nlet toolCount = 0;\nlet kpiCount = 0;\n\n// ============================================================\n// PROCESS INPUT ROWS\n// ============================================================\n\nfor (const item of items) {\n  const data = item.json || {};\n\n  const hasRaciSignal =\n    getField(data, 'Process/Task', 'Process', 'Task') &&\n    getField(data, 'Responsible', 'R');\n\n  const hasToolSignal =\n    getField(data, 'ToolName', 'Tool Name', 'Tool') &&\n    getField(data, 'Purpose', 'Description');\n\n  const metric = getField(data, 'Metric', 'KPI', 'Name');\n  const value = getField(data, 'Value', 'Vale', 'Amount', 'Score');\n\n  // ---- RACI ----\n  if (hasRaciSignal) {\n    currentModelData.org_structure.push({\n      type: 'raci_matrix',\n      process: getField(data, 'Process/Task', 'Process', 'Task') || '',\n      responsible: getField(data, 'Responsible', 'R') || '',\n      accountable: getField(data, 'Accountable', 'A') || '',\n      consulted: getField(data, 'Consulted', 'C') || '',\n      informed: getField(data, 'Informed', 'I') || '',\n      team: getField(data, 'Team', 'Department') || '',\n      tool_used: getField(data, 'Tool Used', 'Tool', 'Tools') || '',\n      frequency: getField(data, 'Frequency') || '',\n      manual_pct: safeNumber(getField(data, 'Manual %', 'Manual')),\n      source: 'google_sheets'\n    });\n    raciCount++;\n    continue;\n  }\n\n  // ---- TOOLS ----\n  if (hasToolSignal) {\n    currentModelData.tools.push({\n      name: getField(data, 'ToolName', 'Tool Name', 'Tool') || '',\n      purpose: getField(data, 'Purpose', 'Description', 'Use') || '',\n      users: safeNumber(getField(data, 'UserCount', 'User Count', 'Users')),\n      overlap_score: safeNumber(getField(data, 'OverlapScore', 'Overlap Score')),\n      annual_cost: safeNumber(getField(data, 'AnnualCost', 'Annual Cost', 'Cost')),\n      source: 'google_sheets'\n    });\n    toolCount++;\n    continue;\n  }\n\n  // ---- KPIs ----\n  if (metric && value !== null) {\n    const metricLower = String(metric).toLowerCase();\n    const numValue = safeNumber(value);\n\n    if (metricLower.includes('turnaround')) {\n      currentModelData.kpis.turnaround_time_avg = numValue;\n    } else if (metricLower.includes('utilization')) {\n      currentModelData.kpis.fte_utilization = numValue;\n    } else if (metricLower.includes('cost')) {\n      currentModelData.kpis.cost_per_asset = numValue;\n    } else if (metricLower.includes('error')) {\n      currentModelData.kpis.error_rate = numValue;\n    } else if (metricLower.includes('volume')) {\n      currentModelData.kpis.volume_per_month = numValue;\n    }\n\n    kpiCount++;\n    continue;\n  }\n\n  // ---- DOCUMENTS ----\n  if (data.mimeType || item.binary) {\n    currentModelData.raw_documents.push({\n      name: data.name || 'Document',\n      type: data.mimeType || 'unknown',\n      source: 'google_drive'\n    });\n  }\n}\n\n// ============================================================\n// FALLBACK ONLY IF TRULY EMPTY\n// ============================================================\n\nif (raciCount === 0 && currentModelData.org_structure.length === 0) {\n  currentModelData.org_structure = [];\n}\n\nif (toolCount === 0 && currentModelData.tools.length === 0) {\n  currentModelData.tools = [];\n}\n\nif (Object.keys(currentModelData.kpis).length === 0) {\n  currentModelData.kpis = {};\n}\n\n// ============================================================\n// DATA QUALITY SCORE\n// ============================================================\n\nconst dataQuality = Math.round(\n  (raciCount > 0 ? 33 : 0) +\n  (toolCount > 0 ? 33 : 0) +\n  (kpiCount > 0 ? 34 : 0)\n);\n\ncurrentModelData.data_quality = dataQuality;\n\n// ============================================================\n// LOGGING\n// ============================================================\n\nconsole.log('Data Cleaner v5 Summary');\nconsole.log('- Client:', resolvedClient);\nconsole.log('- Audit ID:', auditIdFinal);\nconsole.log('- RACI rows:', raciCount);\nconsole.log('- Tools:', toolCount);\nconsole.log('- KPIs:', kpiCount);\nconsole.log('- Data quality:', dataQuality + '%');\n\n// ============================================================\n// RETURN SINGLE ITEM\n// ============================================================\n\nreturn [{ json: currentModelData }];"
      },
      "typeVersion": 2
    },
    {
      "id": "3f8dee15-9d9a-46e2-acb0-0a37cbc07575",
      "name": "2.3 Map AI and Automation Opportunities",
      "type": "@n8n/n8n-nodes-langchain.openAi",
      "position": [
        4700,
        760
      ],
      "parameters": {
        "modelId": {
          "__rl": true,
          "mode": "list",
          "value": "gpt-4.1-mini",
          "cachedResultName": "GPT-4.1-MINI"
        },
        "options": {
          "temperature": 0.4
        },
        "messages": {
          "values": [
            {
              "content": "=You are an AI transformation specialist mapping automation opportunities.\n\nClient: {{ $('Industry Template Selector').first().json.client_name }}\nSector: {{ $('Industry Template Selector').first().json.sector }}\n\nRECOMMENDED AI SOLUTIONS FOR THIS SECTOR:\n{{ $('Industry Template Selector').first().json.sector_ai_solutions.join('\\n- ') }}\n\nCOMPLIANCE REQUIREMENTS:\n{{ $('Industry Template Selector').first().json.sector_compliance.join(', ') }}\n\nBased on this inefficiency analysis:\n```json\n{{ JSON.stringify($('2.2 Analyse Inefficiencies With OpenAI').first().json, null, 2) }}\n```\n\nFor each identified inefficiency, recommend specific AI/automation solutions.\nPrioritize solutions from the recommended list for this sector, but also consider:\n- content production automation tools\n- n8n workflow automations\n- GPT-4o agentic solutions\n- DeepL, Whisper, Vision APIs\n- Custom automation tools\n\nIMPORTANT: Ensure all recommendations comply with {{ $('Industry Template Selector').first().json.sector_compliance.join(', ') }}\n\nReturn as JSON:\n{\n  \"recommendations\": [\n    {\n      \"process\": \"...\",\n      \"ai_fit\": \"High|Medium|Low\",\n      \"recommended_tech\": [\"tool1\", \"tool2\"],\n      \"implementation_complexity\": \"Simple|Moderate|Complex\",\n      \"potential_saving_pct\": 0-100,\n      \"estimated_roi_months\": number,\n      \"description\": \"How this would work\",\n      \"compliance_notes\": \"Any regulatory considerations\"\n    }\n  ],\n  \"sector_summary\": \"Summary of AI opportunities specific to {{ $('Industry Template Selector').first().json.sector }}\"\n}"
            }
          ]
        }
      },
      "typeVersion": 1.7
    },
    {
      "id": "05f72479-fefe-485e-8343-30d53f59823f",
      "name": "2.4a Google Sheets - Benchmarks",
      "type": "n8n-nodes-base.googleSheets",
      "position": [
        3000,
        1010
      ],
      "parameters": {
        "options": {},
        "sheetName": {
          "__rl": true,
          "mode": "name",
          "value": "Benchmarks"
        },
        "documentId": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $('Set Client Config').first().json.master_sheet_id }}"
        }
      },
      "typeVersion": 4.5
    },
    {
      "id": "0074afb1-84af-4ae1-8009-98671f159f62",
      "name": "2.4b Benchmark Comparator",
      "type": "n8n-nodes-base.code",
      "position": [
        5010,
        760
      ],
      "parameters": {
        "jsCode": "function s(v) {\n  if (v === null || v === undefined) return '';\n  if (typeof v === 'string') return v;\n  try { return JSON.stringify(v); } catch (e) { return String(v); }\n}\n\nfunction stripFences(t) {\n  return String(t || '')\n    .replace(/```mermaid\\s*/gi, '')\n    .replace(/```json\\s*/gi, '')\n    .replace(/```/g, '')\n    .trim();\n}\n\nfunction wrapMermaid(diagram) {\n  const body = stripFences(diagram);\n  return '```mermaid\\n' + body + '\\n```';\n}\n\nfunction makeArchitecture(auditId, clientName) {\n  const id = auditId || 'unknown';\n  const cn = clientName || 'unknown';\n  return [\n    'flowchart TB',\n    '  subgraph Intake',\n    '    A[\"Brief intake\"] --> B[\"Triage and validate\"]',\n    '  end',\n    '  subgraph Design',\n    '    B --> C[\"Operating model blueprint\"]',\n    '    C --> D[\"RACI and governance\"]',\n    '  end',\n    '  subgraph Output',\n    '    D --> E[\"Diagrams and reports\"]',\n    '    E --> F[\"Write to Google Sheets\"]',\n    '  end',\n    '  %% audit_id: ' + id,\n    '  %% client_name: ' + cn\n  ].join('\\n');\n}\n\nfunction makeRoadmap(auditId, clientName) {\n  const id = auditId || 'unknown';\n  const cn = clientName || 'unknown';\n  return [\n    'gantt',\n    '  title Operating Model Delivery Roadmap',\n    '  dateFormat  YYYY-MM-DD',\n    '  axisFormat  %d %b',\n    '  section Foundation',\n    '  Data contract and schema      :a1, 2026-01-01, 10d',\n    '  Sheet upsert and dedupe       :a2, after a1, 7d',\n    '  section Build',\n    '  Executive summary and RACI    :b1, after a2, 10d',\n    '  Diagrams and reporting pack   :b2, after b1, 7d',\n    '  section Scale',\n    '  Performance tuning            :c1, after b2, 7d',\n    '  Governance and QA             :c2, after c1, 7d',\n    '  %% audit_id: ' + id,\n    '  %% client_name: ' + cn\n  ].join('\\n');\n}\n\nfunction makeProcessFlow(auditId, clientName) {\n  const id = auditId || 'unknown';\n  const cn = clientName || 'unknown';\n  return [\n    'flowchart LR',\n    '  I[\"Inputs\"] --> P[\"Process\"] --> O[\"Outputs\"]',\n    '  subgraph Inputs',\n    '    I1[\"Client config\"]',\n    '    I2[\"Audit data\"]',\n    '  end',\n    '  subgraph Process',\n    '    P1[\"Generate operating model\"]',\n    '    P2[\"Generate executive summary\"]',\n    '    P3[\"Generate RACI\"]',\n    '    P4[\"Generate diagrams\"]',\n    '    P5[\"Write to Sheets\"]',\n    '  end',\n    '  subgraph Outputs',\n    '    O1[\"Operating model JSON\"]',\n    '    O2[\"Executive summary\"]',\n    '    O3[\"RACI\"]',\n    '    O4[\"Mermaid diagrams\"]',\n    '  end',\n    '  I1 --> P1',\n    '  I2 --> P1',\n    '  P1 --> P2 --> P3 --> P4 --> P5',\n    '  P5 --> O1',\n    '  P5 --> O2',\n    '  P5 --> O3',\n    '  P5 --> O4',\n    '  %% audit_id: ' + id,\n    '  %% client_name: ' + cn\n  ].join('\\n');\n}\n\nfunction makeTechStack(auditId, clientName) {\n  const id = auditId || 'unknown';\n  const cn = clientName || 'unknown';\n  return [\n    'flowchart TB',\n    '  U[\"Users and SMEs\"] --> N[\"n8n workflow\"]',\n    '  N --> L[\"LLM calls\"]',\n    '  N --> S[\"Google Sheets\"]',\n    '  L --> R[\"Model outputs\"]',\n    '  S --> R',\n    '  subgraph LLM',\n    '    L1[\"GPT model\"]',\n    '  end',\n    '  subgraph Storage',\n    '    S1[\"Sheets tabs as store\"]',\n    '  end',\n    '  %% audit_id: ' + id,\n    '  %% client_name: ' + cn\n  ].join('\\n');\n}\n\nconst inputItem = $input.first().json || {};\n\nconst audit_id = s(inputItem.audit_id || inputItem.auditId || inputItem.audit || '').trim() || 'unknown';\nconst client_name = s(inputItem.client_name || inputItem.clientName || inputItem.client || '').trim() || 'unknown';\nconst created_at = new Date().toISOString();\nconst render_hint = 'mermaid';\n\nconst diagrams = [\n  { diagram_type: 'architecture', mermaid_code: wrapMermaid(makeArchitecture(audit_id, client_name)) },\n  { diagram_type: 'roadmap', mermaid_code: wrapMermaid(makeRoadmap(audit_id, client_name)) },\n  { diagram_type: 'process_flow', mermaid_code: wrapMermaid(makeProcessFlow(audit_id, client_name)) },\n  { diagram_type: 'tech_stack', mermaid_code: wrapMermaid(makeTechStack(audit_id, client_name)) },\n];\n\nreturn diagrams.map(d => {\n  return {\n    json: {\n      row_key: client_name + '|' + audit_id + '|' + d.diagram_type,\n      audit_id,\n      diagram_type: d.diagram_type,\n      mermaid_code: d.mermaid_code,\n      render_hint,\n      created_at,\n    }\n  };\n});"
      },
      "typeVersion": 2
    },
    {
      "id": "751ec0b2-259d-4d34-9de1-ed022269d57a",
      "name": "Merge Analysis Results",
      "type": "n8n-nodes-base.merge",
      "position": [
        4390,
        1010
      ],
      "parameters": {},
      "typeVersion": 3
    },
    {
      "id": "9ed62c83-514e-442d-93f5-8ff2cc1e154a",
      "name": "3.1 Generate Target Operating Model",
      "type": "@n8n/n8n-nodes-langchain.openAi",
      "position": [
        990,
        2960
      ],
      "parameters": {
        "modelId": {
          "__rl": true,
          "mode": "list",
          "value": "gpt-4.1-mini",
          "cachedResultName": "GPT-4.1-MINI"
        },
        "options": {
          "maxTokens": 5000,
          "temperature": 0.3
        },
        "messages": {
          "values": [
            {
              "content": "=You are an enterprise operating model architect specialising in AI-enabled marketing, content, and workflow ecosystems.\n\nYou design implementable, financially grounded, governance-safe target operating models for global organisations.\n\nYou must:\n\nProduce enterprise-grade structures aligned to business outcomes.\n\nDefine clear teams, roles, responsibilities and AI augmentation.\n\nDesign detailed future-state process flows with ownership and automation level.\n\nSpecify technology architecture including AI agents and orchestration workflows.\n\nQuantify impact where possible.\n\nEnsure governance, compliance and change management are addressed.\n\nAvoid generic statements.\n\nOutput strictly valid JSON only.\n\nNever include explanations, markdown, or commentary outside the JSON schema provided by the user.\n\nUSER PROMPT\n\nClient: {{ $json.client_name || \"\" }}\nSector: {{ $json.sector || \"\" }}\nMaturity Stage: {{ $json.maturity_stage || \"\" }}\nMarket Count: {{ $json.market_count || \"\" }}\n\nANALYSIS INPUT:\n{{ JSON.stringify($json, null, 2) }}\n\nDesign a COMPREHENSIVE AI-enabled target operating model aligned to the client context above.\n\nOutput ONLY valid JSON using the exact schema provided below.\n\n{\n\"organization_structure\": {\n\"model_type\": \"Hub-and-Spoke\",\n\"swim_lanes\": [\n{\n\"team\": \"Team Name\",\n\"responsibilities\": [],\n\"ai_augmentation\": \"\",\n\"headcount\": 0,\n\"key_roles\": []\n}\n],\n\"new_roles\": [],\n\"roles_to_eliminate\": []\n},\n\"process_flows\": [],\n\"technology_architecture\": {\n\"future_stack\": {\n\"core_platforms\": [],\n\"ai_layer\": []\n},\n\"ai_agents\": [],\n\"n8n_workflows\": [],\n\"tools_to_retire\": [],\n\"tools_to_add\": []\n},\n\"new_raci_matrix\": [],\n\"transformation_roadmap\": {\n\"phase_1_quick_wins\": {\n\"timeline\": \"\",\n\"objectives\": [],\n\"deliverables\": [],\n\"automation_implementations\": [],\n\"agent_deployments\": []\n},\n\"phase_2_foundation\": {\n\"timeline\": \"\",\n\"objectives\": [],\n\"platform_deployments\": []\n},\n\"phase_3_scale\": {\n\"timeline\": \"\",\n\"market_rollouts\": []\n},\n\"phase_4_optimize\": {\n\"timeline\": \"\",\n\"continuous_improvements\": []\n}\n},\n\"success_metrics\": {\n\"kpis_to_track\": []\n},\n\"change_management\": {\n\"training_required\": [],\n\"risk_mitigation\": []\n}\n}\n\nCRITICAL:\n\nReturn ONLY valid JSON.\n\nDo not add commentary.\n\nDo not wrap in markdown.\n\nDo not explain reasoning.\n\nDo not add fields outside this schema."
            }
          ]
        }
      },
      "typeVersion": 1.7
    },
    {
      "id": "50c8cd39-a95c-4437-9d4e-e28e5a9d365b",
      "name": "3.2 Financial Model Deep-Dive",
      "type": "n8n-nodes-base.code",
      "position": [
        1300,
        2960
      ],
      "parameters": {
        "jsCode": "// Financial Model Deep-Dive - CFO-Grade Financial Analysis\n// Hardened Version - Stable Client + Audit Resolution\n\n// ============================================================\n// SECTION 1: HELPER FUNCTIONS\n// ============================================================\n\nfunction parseAIResponse(content) {\n  if (!content) return {};\n  let cleaned = content.trim();\n\n  if (cleaned.startsWith('```json')) cleaned = cleaned.slice(7);\n  else if (cleaned.startsWith('```')) cleaned = cleaned.slice(3);\n  if (cleaned.endsWith('```')) cleaned = cleaned.slice(0, -3);\n\n  cleaned = cleaned.trim();\n\n  try {\n    return JSON.parse(cleaned);\n  } catch {\n    return {};\n  }\n}\n\nfunction safeGetNode(nodeName) {\n  try {\n    const node = $(nodeName);\n    if (node && node.first) return node.first().json;\n  } catch {}\n  return null;\n}\n\n// ============================================================\n// SECTION 2: SAFE INPUT RESOLUTION\n// ============================================================\n\nconst baseInput = $input.first()?.json || {};\n\nconst dynamicCfg = safeGetNode('Optional - Map Queue Row to Config') || {};\nconst clientConfig = safeGetNode('Set Client Config') || {};\nconst cleanedData = safeGetNode('2.1 Data Cleaner') || baseInput || {};\nconst ineffNode = safeGetNode('2.2 Inefficiency Scorer - GPT-4o');\nconst aiNode = safeGetNode('2.3 Map AI and Automation Opportunities');\nconst benchmarkData = safeGetNode('2.4b Benchmark Comparator') || {};\n\nlet inefficiencyData = {};\nlet aiRecommendations = {};\n\nif (ineffNode?.message?.content) {\n  inefficiencyData = parseAIResponse(ineffNode.message.content);\n}\n\nif (aiNode?.message?.content) {\n  aiRecommendations = parseAIResponse(aiNode.message.content);\n}\n\n// ---- Hardened Client + Audit Resolution ----\n\nconst resolvedClient =\n  clientConfig.client_name ||\n  dynamicCfg.client_name ||\n  cleanedData.client_name ||\n  baseInput.client_name ||\n  baseInput.Client_Name ||\n  \"Unknown Client\";\n\nconst resolvedAuditId =\n  cleanedData.audit_id ||\n  clientConfig.audit_id ||\n  dynamicCfg.audit_id ||\n  baseInput.audit_id ||\n  baseInput.Audit_ID ||\n  `AUDIT_${Date.now()}`;\n\n// ============================================================\n// SECTION 3: CONFIGURATION\n// ============================================================\n\nconst cfgNode = safeGetNode('Set Client Config') || dynamicCfg || clientConfig || {};\nconst config = {\n  avg_fte_cost: Number(cfgNode.avg_fte_cost || 85000),\n  hours_per_fte_year: Number(cfgNode.hours_per_fte_year || 1800),\n  software_license_annual: Number(cfgNode.software_license_annual || 25000),\n  integration_cost_per_system: Number(cfgNode.integration_cost_per_system || 15000),\n  training_cost_per_fte: Number(cfgNode.training_cost_per_fte || 2500),\n  change_management_pct: Number(cfgNode.change_management_pct || 0.15),\n  discount_rate: Number(cfgNode.discount_rate || 0.10),\n  tax_rate: 0.25,\n  inflation_rate: 0.03,\n  implementation_risk_buffer: Number(cfgNode.implementation_risk_buffer || 0.20),\n  benefit_realization_factor: Number(cfgNode.benefit_realization_factor || 0.85),\n  analysis_years: Number(cfgNode.analysis_years || 5),\n  market_count: Number(cfgNode.market_count || 5)\n};\n\n// ============================================================\n// SECTION 4: TCO CALCULATION\n// ============================================================\n\nfunction calculateTCO(scenario) {\n\n  const complexity_multiplier =\n    scenario === 'cautious' ? 0.5 :\n    scenario === 'aggressive' ? 1.8 :\n    1.0;\n\n  const recommendations = aiRecommendations.recommendations || [];\n\n  const simpleCount = recommendations.filter(r => r.implementation_complexity === 'Simple').length;\n  const moderateCount = recommendations.filter(r => r.implementation_complexity === 'Moderate').length;\n  const complexCount = recommendations.filter(r => r.implementation_complexity === 'Complex').length;\n\n  const implementation =\n    (2 + Math.floor(complexCount / 2)) * config.software_license_annual * complexity_multiplier +\n    (simpleCount * 5000 + moderateCount * 15000 + complexCount * 40000) * complexity_multiplier +\n    20000 * complexity_multiplier;\n\n  const contingency = implementation * config.implementation_risk_buffer;\n\n  const implementationTotal = Math.round(implementation + contingency);\n\n  const recurring = Math.round(\n    (implementationTotal * 0.3) +\n    config.avg_fte_cost * (scenario === 'aggressive' ? 1.5 : scenario === 'hybrid' ? 1 : 0.5)\n  );\n\n  return {\n    implementation_total: implementationTotal,\n    annual_recurring: recurring,\n    five_year_total: implementationTotal + (recurring * config.analysis_years)\n  };\n}\n\n// ============================================================\n// SECTION 5: BENEFIT CALCULATION\n// ============================================================\n\nfunction calculateBenefits(scenario) {\n\n  const scenario_factor =\n    scenario === 'cautious' ? 0.4 :\n    scenario === 'aggressive' ? 0.8 :\n    0.6;\n\n  const inefficiencies = inefficiencyData.inefficiencies || [];\n  const total_inefficiency_cost = inefficiencies.reduce((sum, i) => sum + (i.annual_cost || 50000), 0);\n\n  const annual_benefit = Math.round(\n    total_inefficiency_cost *\n    scenario_factor *\n    config.benefit_realization_factor\n  );\n\n  const fte_equivalent = Math.round((annual_benefit / config.avg_fte_cost) * 10) / 10;\n\n  return {\n    total_annual: annual_benefit,\n    fte_equivalent\n  };\n}\n\n// ============================================================\n// SECTION 6: FINANCIAL METRICS\n// ============================================================\n\nfunction calculateNPV(initial, annual, recurring) {\n  let npv = -initial;\n  for (let y = 1; y <= config.analysis_years; y++) {\n    const cash = annual - recurring;\n    npv += cash / Math.pow(1 + config.discount_rate, y);\n  }\n  return Math.round(npv);\n}\n\nfunction calculateIRR(initial, annual, recurring) {\n  const net = annual - recurring;\n  if (net <= 0) return 0;\n  return Math.round((net / initial) * 100);\n}\n\nfunction calculatePayback(initial, annual, recurring) {\n  const net = annual - recurring;\n  if (net <= 0) return null;\n  return Math.round((initial / net) * 12);\n}\n\n// ============================================================\n// SECTION 7: BUILD SCENARIO\n// ============================================================\n\nfunction buildScenario(name) {\n\n  const tco = calculateTCO(name);\n  const benefits = calculateBenefits(name);\n\n  const npv = calculateNPV(\n    tco.implementation_total,\n    benefits.total_annual,\n    tco.annual_recurring\n  );\n\n  const irr = calculateIRR(\n    tco.implementation_total,\n    benefits.total_annual,\n    tco.annual_recurring\n  );\n\n  const payback = calculatePayback(\n    tco.implementation_total,\n    benefits.total_annual,\n    tco.annual_recurring\n  );\n\n  const fiveYearROI = Math.round(\n    ((benefits.total_annual * config.analysis_years - tco.five_year_total) /\n    tco.implementation_total) * 100\n  );\n\n  return {\n    scenario_name: name,\n    total_investment: tco.five_year_total,\n    annual_benefit: benefits.total_annual,\n    npv,\n    irr_percentage: irr,\n    payback_months: payback,\n    five_year_roi: fiveYearROI,\n    fte_saved: benefits.fte_equivalent\n  };\n}\n\n// ============================================================\n// SECTION 8: EXECUTION\n// ============================================================\n\nconst cautious = buildScenario('cautious');\nconst hybrid = buildScenario('hybrid');\nconst aggressive = buildScenario('aggressive');\n\nconst result = {\n\n  audit_id: resolvedAuditId,\n  client_name: resolvedClient,\n  analysis_date: new Date().toISOString(),\n\n  recommended_scenario: 'hybrid',\n\n  scenario_comparison: {\n    cautious,\n    hybrid,\n    aggressive\n  },\n\n  implementation_cost: hybrid.total_investment,\n  annual_saving: hybrid.annual_benefit,\n  fte_saved: hybrid.fte_saved,\n  efficiency_gain_pct: Math.round(\n    (hybrid.annual_benefit /\n    (hybrid.annual_benefit + calculateTCO('hybrid').annual_recurring)) * 100\n  ),\n  three_year_roi: hybrid.five_year_roi,\n  payback_period_months: hybrid.payback_months\n};\n\nreturn [{ json: result }];"
      },
      "typeVersion": 2
    },
    {
      "id": "0c7e58e9-6c86-4252-9130-30af2b09b231",
      "name": "3.3 Visual Schema Builder",
      "type": "n8n-nodes-base.code",
      "position": [
        1610,
        2960
      ],
      "parameters": {
        "jsCode": "// Stable Aggregation Node\n// No hard dependency on Set Client Config\n// Works even if executed mid-workflow\n\nconst safeNodeJson = (nodeName) => {\n  try {\n    if ($(nodeName).isExecuted) {\n      return $(nodeName).first().json;\n    }\n  } catch (e) {}\n  return null;\n};\n\nconst base = $input.first()?.json || {};\n\n// Prefer Optional - Map Queue Row to Config\nconst dynamicCfg = safeNodeJson(\"Optional - Map Queue Row to Config\");\nconst setCfg = safeNodeJson(\"Set Client Config\");\n\nconst blueprint =\n  safeNodeJson(\"3.1 Generate Target Operating Model\") ||\n  base.blueprint ||\n  {};\n\nconst roiData =\n  safeNodeJson(\"3.2 Financial Model Deep-Dive\") ||\n  base.financial_model ||\n  {};\n\nconst cfg = {\n  ...base,\n  ...(dynamicCfg || {}),\n  ...(setCfg || {})\n};\n\nconst clientName =\n  cfg.client_name ||\n  cfg.client ||\n  cfg.organisation_name ||\n  \"Unknown Client\";\n\nconst auditId =\n  cfg.audit_id ||\n  roiData.audit_id ||\n  blueprint.audit_id ||\n  base.audit_id ||\n  \"\";\n\nreturn [{\n  json: {\n    client_name: clientName,\n    audit_id: auditId,\n    blueprint,\n    roi: roiData\n  }\n}];"
      },
      "typeVersion": 2
    },
    {
      "id": "9b38d8f1-49f7-44ee-ac92-1d169a915e2b",
      "name": "3.3b Change Management Framework",
      "type": "n8n-nodes-base.code",
      "position": [
        2230,
        2960
      ],
      "parameters": {
        "jsCode": "const safeNode = (name) => {\n  try {\n    if ($(name).isExecuted) return $(name).first().json;\n  } catch (e) {}\n  return null;\n};\n\nfunction parseAIResponse(content) {\n  if (!content) return {};\n  let cleaned = String(content).trim()\n    .replace(/^```json/i, '')\n    .replace(/^```/, '')\n    .replace(/```$/, '')\n    .trim();\n  try { return JSON.parse(cleaned); } catch { return {}; }\n}\n\nconst base = $input.first()?.json || {};\nconst cfg = safeNode('Set Client Config') || safeNode('Optional - Map Queue Row to Config') || base;\nconst financialNode = safeNode('3.2 Financial Model Deep-Dive') || {};\nconst blueprintNode = safeNode('3.1 Generate Target Operating Model') || {};\n\nlet blueprint = {};\nif (blueprintNode?.message?.content) blueprint = parseAIResponse(blueprintNode.message.content);\n\nlet stakeholders = [];\ntry {\n  stakeholders = JSON.parse(cfg.stakeholders_json || '[]');\n  if (!Array.isArray(stakeholders)) stakeholders = [];\n} catch {\n  stakeholders = [];\n}\n\nconst adkarScores = {\n  awareness: Number(cfg.adkar_awareness || 5),\n  desire: Number(cfg.adkar_desire || 5),\n  knowledge: Number(cfg.adkar_knowledge || 5),\n  ability: Number(cfg.adkar_ability || 5),\n  reinforcement: Number(cfg.adkar_reinforcement || 5)\n};\n\nconst adkarOverall = Math.round(\n  (adkarScores.awareness + adkarScores.desire + adkarScores.knowledge +\n   adkarScores.ability + adkarScores.reinforcement) / 5\n);\n\nconst readinessLevel =\n  adkarOverall >= 7 ? 'Ready' :\n  adkarOverall >= 5 ? 'Moderate Risk' : 'High Risk';\n\nconst fteSaved =\n  financialNode?.scenario_comparison?.hybrid?.fte_saved ||\n  financialNode?.scenarios?.hybrid?.fte_saved || 0;\n\nconst trainingNeeds = [\n  { role: 'AI / Automation Supervisors', headcount: Math.max(Math.ceil(fteSaved * 0.3), 1), training_hours: 40 },\n  { role: 'Automation Builders', headcount: Math.max(Math.ceil(fteSaved * 0.2), 1), training_hours: 40 },\n  { role: 'Operational Users', headcount: Math.max(Math.ceil(fteSaved), 1), training_hours: 12 }\n];\n\nconst totalTrainingHours = trainingNeeds.reduce((sum, t) => sum + (t.training_hours * t.headcount), 0);\nconst hourlyTrainingCost = Number(cfg.training_cost_per_fte || 2500) / 40;\nconst totalTrainingCost = Math.round(totalTrainingHours * hourlyTrainingCost);\n\nreturn [{\n  json: {\n    client_name: cfg.client_name || 'Example Organisation',\n    audit_id: cfg.audit_id || '',\n    stakeholder_summary: {\n      total: stakeholders.length,\n      supportive: stakeholders.filter(s => /support|champion/i.test(String(s.current_stance))).length,\n      resistant: stakeholders.filter(s => /resist/i.test(String(s.current_stance))).length\n    },\n    stakeholders,\n    adkar_assessment: {\n      scores: adkarScores,\n      overall_score: adkarOverall,\n      readiness_level: readinessLevel\n    },\n    training_summary: {\n      total_hours: totalTrainingHours,\n      estimated_cost: totalTrainingCost,\n      training_needs: trainingNeeds\n    },\n    blueprint\n  }\n}];"
      },
      "typeVersion": 2
    },
    {
      "id": "b541585e-4dc3-43a5-9dc6-a46af763fe2b",
      "name": "3.4 Generate Executive Transformation Report",
      "type": "@n8n/n8n-nodes-langchain.openAi",
      "position": [
        990,
        3460
      ],
      "parameters": {
        "modelId": {
          "__rl": true,
          "mode": "list",
          "value": "gpt-4.1-mini",
          "cachedResultName": "GPT-4.1-MINI"
        },
        "options": {
          "maxTokens": 8000,
          "temperature": 0.4
        },
        "messages": {
          "values": [
            {
              "content": "=Client: {{ $('Optional - Map Queue Row to Config').first().json.client_name }}\nSector: {{ $('Optional - Map Queue Row to Config').first().json.sector }}\nMaturity Stage: {{ $('Optional - Map Queue Row to Config').first().json.maturity_stage }}\n\nData Sources:\n\nOperating Model Blueprint: {{ $json.blueprint_content }}\n\nFinancial Scenario Comparison: {{ JSON.stringify($json.financial_scenarios, null, 2) }}\n\nInefficiency Analysis: {{ $json.inefficiency_content }}\n\nAI Recommendations: {{ $json.recommendations_content }}\n\nFINANCIAL TABLES (Include these EXACTLY in Section 4):\n\n{{ $json.financial_tables.tco_table }}\n\n{{ $json.financial_tables.benefits_table }}\n\n{{ $json.financial_tables.cashflow_table }}\n\n{{ $json.financial_tables.sensitivity_table }}\n\nCreate a COMPREHENSIVE 8\u201310 page executive summary following standard consulting report structure:\n\n{{ $('Optional - Map Queue Row to Config').first().json.client_name }} AI-Enabled Operating Model Transformation\nExecutive Summary & Transformation Roadmap\n\nPrepared by: AI Strategy & Operations Team\nDate: {{ $now.format('MMMM DD, YYYY') }}\nConfidential\n\n1. EXECUTIVE OVERVIEW\n\n1.1 Situation Analysis\n2\u20133 paragraphs covering current state challenges, market context, urgency.\n\n1.2 Transformation Opportunity\n2\u20133 paragraphs covering AI-enabled future state and strategic alignment.\n\n1.3 Recommended Approach\n3\u20134 paragraphs describing Hybrid scenario, phased rollout, critical success factors.\n\n1.4 Expected Business Impact\n\nPresent key metrics from financial_scenarios.hybrid:\n\n5-Year NPV: ${{ $json.financial_scenarios.hybrid.npv.toLocaleString() }}\n\nIRR: {{ $json.financial_scenarios.hybrid.irr }}%\n\nPayback Period: {{ $json.financial_scenarios.hybrid.payback_months }} months\n\n5-Year ROI: {{ $json.financial_scenarios.hybrid.five_year_roi }}%\n\nTotal Investment: ${{ $json.financial_scenarios.hybrid.investment.toLocaleString() }}\n\nAnnual Benefit (Year 3): ${{ $json.financial_scenarios.hybrid.annual_benefit.toLocaleString() }}\n\nFTE Equivalent Savings: {{ $json.financial_scenarios.hybrid.fte_saved }} FTEs\n\n2. CURRENT STATE ASSESSMENT\n\n2.1 Operating Model Maturity\nAnalyze the \"{{ $('Optional - Map Queue Row to Config').first().json.maturity_stage }}\" stage operationally.\n\n2.2 Key Inefficiencies & Pain Points\n\nCreate table:\n\n| Process | Category | Annual Cost Impact | Automation Readiness | Priority |\n\nExtract from inefficiency_content.\n\nDetail top 5\u20137 inefficiencies including Description, Impact, Root Cause, Urgency.\n\n2.3 Cost of Inaction\nQuantify annual cost and 3\u20135 year compounding impact.\n\n3. FUTURE STATE VISION\n\n3.1 AI-Enabled Operating Model Overview\nDescribe architecture and orchestration.\n\n3.2 Core Capabilities Enabled\n6\u20138 new measurable capabilities.\n\n3.3 AI Agents & Automation Architecture\n\nCreate table:\n\n| Agent Name | Platform | Responsibilities | Integration Points | Human Touchpoints |\n\nInclude 6\u20138 agents.\n\n3.4 n8n Workflow Automation\n\nCreate table:\n\n| Workflow Name | Purpose | Trigger | Systems Connected | Frequency |\n\nInclude 6\u20138 workflows.\n\n3.5 New RACI Matrix\n\n| Process | AI Agent | Human Reviewer | Manager | Technology |\n\nShow AI moving into Responsible/Accountable roles where appropriate.\n\n4. FINANCIAL ANALYSIS & ROI\n\nCRITICAL: Include ALL financial tables exactly as provided above.\n\n4.1 TCO Analysis\nInclude TCO table exactly. Provide narrative.\n\n4.2 Benefits Analysis\nInclude benefits table exactly. Explain direct, productivity, strategic value.\n\n4.3 5-Year Cash Flow\nInclude cashflow table exactly. Explain ramp and break-even.\n\n4.4 Scenario Comparison\nCreate comparison narrative across Cautious, Hybrid, Aggressive using financial_scenarios object.\n\n4.5 Sensitivity Analysis\nInclude sensitivity table exactly. Explain risk-adjusted returns.\n\n4.6 Key Financial Assumptions\n\n| Assumption | Value | Rationale |\n\nUse assumptions object from $json.\n\n4.7 Recommendation\nJustify Hybrid scenario using NPV, IRR, payback and risk balance.\n\n5. IMPLEMENTATION ROADMAP\n\nPhase 1\u20134 sequencing with governance.\n\n6. RISKS & MITIGATION\n\nInclude risk matrix table.\n\n7. GOVERNANCE & DECISION FRAMEWORK\n8. NEXT STEPS & CALL TO ACTION"
            },
            {
              "role": "system",
              "content": "You are a senior management consultant creating a comprehensive executive summary for a C-suite AI transformation engagement. This is a professional deliverable document. Write in authoritative, data-driven, CFO-ready tone"
            }
          ]
        }
      },
      "typeVersion": 1.7
    },
    {
      "id": "a9db943f-b5a3-4d14-b6e5-2efc4dce035a",
      "name": "Optional - Send Slack Summary",
      "type": "n8n-nodes-base.slack",
      "disabled": true,
      "position": [
        6590,
        2960
      ],
      "parameters": {
        "text": "=\ud83c\udfaf AI Operating Model Audit Complete\n\nClient: {{ $if($(\"Set Client Config\").isExecuted, $(\"Set Client Config\").first().json.client_name, ($json.client_name || \"Unknown Client\")) }}\nSector: {{ $if($(\"Set Client Config\").isExecuted, $(\"Set Client Config\").first().json.sector, ($json.sector || \"Unknown\")) }}\nMaturity: {{ $if($(\"Set Client Config\").isExecuted, $(\"Set Client Config\").first().json.maturity_stage, ($json.maturity_stage || \"\")) }}\nMarkets: {{ $if($(\"Set Client Config\").isExecuted, $(\"Set Client Config\").first().json.market_count, ($json.market_count || \"\")) }}\n\nAudit ID: {{ $if($(\"2.1 Data Cleaner\").isExecuted, $(\"2.1 Data Cleaner\").first().json.audit_id, ($json.audit_id || \"\")) }}\nStatus: Completed\nCreated At: {{ $now.toISO() }}\n\nRecommended Scenario: Hybrid\nAnnual Saving: {{ $if($(\"3.2 Financial Model Deep-Dive\").isExecuted, $(\"3.2 Financial Model Deep-Dive\").first().json.scenario_comparison.hybrid.annual_benefit, ($json.scenario_comparison?.hybrid?.annual_benefit || \"\")) }}\nPayback Months: {{ $if($(\"3.2 Financial Model Deep-Dive\").isExecuted, $(\"3.2 Financial Model Deep-Dive\").first().json.scenario_comparison.hybrid.payback_months, ($json.scenario_comparison?.hybrid?.payback_months || \"\")) }}\n5 Year ROI: {{ $if($(\"3.2 Financial Model Deep-Dive\").isExecuted, $(\"3.2 Financial Model Deep-Dive\").first().json.scenario_comparison.hybrid.five_year_roi, ($json.scenario_comparison?.hybrid?.five_year_roi || \"\")) }}\nNPV: {{ $if($(\"3.2 Financial Model Deep-Dive\").isExecuted, $(\"3.2 Financial Model Deep-Dive\").first().json.scenario_comparison.hybrid.npv, ($json.scenario_comparison?.hybrid?.npv || \"\")) }}\nIRR: {{ $if($(\"3.2 Financial Model Deep-Dive\").isExecuted, $(\"3.2 Financial Model Deep-Dive\").first().json.scenario_comparison.hybrid.irr, ($json.scenario_comparison?.hybrid?.irr || \"\")) }}\n\nExecutive Summary Preview:\n{{ $if($(\"3.4 Generate Executive Transformation Report\").isExecuted, $(\"3.4 Generate Executive Transformation Report\").first().json.message.content.substring(0, 1200), (($json.message?.content || $json.executive_summary || \"\").substring(0, 1200))) }}",
        "select": "channel",
        "channelId": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $('Set Client Config').first().json.slack_channel_id }}"
        },
        "otherOptions": {},
        "authentication": "oAuth2"
      },
      "executeOnce": true,
      "typeVersion": 2.2
    },
    {
      "id": "7caa8fed-ab3c-4434-941a-72c0fa4ec08d",
      "name": "Optional - Send Email Summary",
      "type": "n8n-nodes-base.gmail",
      "disabled": true,
      "position": [
        6900,
        2960
      ],
      "parameters": {
        "sendTo": "={{ $('Set Client Config').first().json.notification_email }}",
        "message": "={{ $('Final Payload').first().json.email_body }}",
        "options": {
          "appendAttribution": true
        },
        "subject": "={{ $('Final Payload').first().json.email_subject || 'AI Operating Model Assessment Complete' }}"
      },
      "executeOnce": true,
      "typeVersion": 2.1
    },
    {
      "id": "3dca08c0-57fd-403e-8db4-eed57e63d371",
      "name": "Optional - Store Assessment in Supabase",
      "type": "n8n-nodes-base.supabase",
      "disabled": true,
      "position": [
        6590,
        3210
      ],
      "parameters": {
        "tableId": "creative_memory"
      },
      "typeVersion": 1
    },
    {
      "id": "3622e126-3564-4c28-8bab-2840403c95a8",
      "name": "Optional - Extract Reusable Patterns",
      "type": "n8n-nodes-base.code",
      "disabled": true,
      "position": [
        6900,
        3210
      ],
      "parameters": {
        "jsCode": "// ===============================\n// SAFE NODE ACCESS\n// ===============================\n\nfunction safeNodeJson(nodeName) {\n  try {\n    const node = $(nodeName);\n    if (node && node.isExecuted) {\n      return node.first().json || {};\n    }\n  } catch (e) {}\n  return {};\n}\n\nfunction safeContent(nodeName) {\n  try {\n    const node = $(nodeName);\n    if (node && node.isExecuted) {\n      return node.first().json?.message?.content || \"\";\n    }\n  } catch (e) {}\n  return \"\";\n}\n\nfunction truncate(text, length = 5000) {\n  if (!text) return \"\";\n  return String(text).substring(0, length);\n}\n\n// ===============================\n// FETCH UPSTREAM DATA SAFELY\n// ===============================\n\nconst clientConfig = safeNodeJson(\"Set Client Config\");\nconst dataCleaner = safeNodeJson(\"2.1 Data Cleaner\");\nconst inefficiencyScorer = safeNodeJson(\"2.2 Inefficiency Scorer - GPT-4o\");\nconst aiFitMapper = safeNodeJson(\"2.3 Map AI and Automation Opportunities\");\nconst blueprint = safeNodeJson(\"3.1 Generate Target Operating Model\");\nconst roiSimulator = safeNodeJson(\"3.2 Financial Model Deep-Dive\");\n\n// ===============================\n// EXTRACT CONTENT\n// ===============================\n\nconst inefficiencies = safeContent(\"2.2 Inefficiency Scorer - GPT-4o\");\nconst recommendations = safeContent(\"2.3 Map AI and Automation Opportunities\");\nconst blueprintContent = safeContent(\"3.1 Generate Target Operating Model\");\n\n// ===============================\n// NORMALISE FINANCIAL STRUCTURE\n// ===============================\n\nconst scenarios = roiSimulator.scenario_comparison || roiSimulator.scenarios || {};\nconst hybrid = scenarios.hybrid || {};\n\nconst financialTables = roiSimulator.financial_tables || {\n  tco_table: \"\",\n  benefits_table: \"\",\n  cashflow_table: \"\",\n  sensitivity_table: \"\"\n};\n\nconst assumptions = roiSimulator.assumptions || {};\n\n// ===============================\n// BUILD CONTEXT OBJECT\n// ===============================\n\nconst context = {\n  client_name: clientConfig.client_name || dataCleaner.client_name || $json.client_name || \"Unknown Client\",\n  sector: clientConfig.sector || dataCleaner.sector || $json.sector || \"Unknown\",\n  maturity_stage: clientConfig.maturity_stage || $json.maturity_stage || \"\",\n  audit_id: dataCleaner.audit_id || clientConfig.audit_id || $json.audit_id || \"\",\n  audit_date: new Date().toISOString(),\n\n  blueprint_content: truncate(blueprintContent),\n  inefficiency_content: truncate(inefficiencies),\n  recommendations_content: truncate(recommendations),\n\n  financial_scenarios: scenarios,\n  financial_tables: financialTables,\n  assumptions: assumptions,\n\n  recommended_scenario: roiSimulator.recommended_scenario || \"hybrid\",\n\n  hybrid_metrics: {\n    three_year_roi: hybrid.three_year_roi || hybrid.five_year_roi || 0,\n    npv: hybrid.npv || 0,\n    irr: hybrid.irr || 0,\n    payback_months: hybrid.payback_months || 0,\n    investment: hybrid.investment || hybrid.implementation_cost || 0,\n    annual_benefit: hybrid.annual_benefit || hybrid.annual_saving || 0,\n    fte_saved: hybrid.fte_saved || 0\n  },\n\n  lessons_learned: [\n    \"AI transformation for \" + (clientConfig.sector || \"Unknown sector\"),\n    \"Maturity stage: \" + (clientConfig.maturity_stage || \"Unspecified\"),\n    \"Hybrid ROI: \" + (hybrid.three_year_roi || hybrid.five_year_roi || 0) + \"%\"\n  ]\n};\n\n// ===============================\n// LOG FOR DEBUG\n// ===============================\n\nconsole.log(\"Executive Summary Context Built:\");\nconsole.log(\"Client:\", context.client_name);\nconsole.log(\"Sector:\", context.sector);\nconsole.log(\"Scenario Keys:\", Object.keys(context.financial_scenarios || {}));\n\n// ===============================\n// RETURN SINGLE STRUCTURED OBJECT\n// ===============================\n\nreturn [{ json: context }];"
      },
      "typeVersion": 2
    },
    {
      "id": "d2268325-5960-49cf-922d-abacfcf26d25",
      "name": "Optional - Store Patterns in Supabase",
      "type": "n8n-nodes-base.supabase",
      "disabled": true,
      "position": [
        7210,
        3210
      ],
      "parameters": {
        "tableId": "creative_memory"
      },
      "typeVersion": 1
    },
    {
      "id": "c4588a3f-b1dd-4b06-b8b4-30935d9d945a",
      "name": "4.1 Write Operating Model to Google Sheets",
      "type": "n8n-nodes-base.googleSheets",
      "position": [
        3800,
        3460
      ],
      "parameters": {
        "columns": {
          "value": {
            "sector": "={{ $json.sector }}",
            "row_key": "={{ $json.row_key }}",
            "audit_id": "={{ $json.audit_id }}",
            "fte_saved": "={{ $json.fte_saved }}",
            "created_at": "={{ $json.created_at }}",
            "hybrid_npv": "={{ $json.hybrid_npv }}",
            "client_name": "={{ $json.client_name }}",
            "cautious_npv": "={{ $json.cautious_npv }}",
            "annual_saving": "={{ $json.annual_saving }}",
            "run_timestamp": "={{ $json.run_timestamp }}",
            "aggressive_npv": "={{ $json.aggressive_npv }}",
            "hybrid_irr_pct": "={{ $json.hybrid_irr_pct }}",
            "maturity_stage": "={{ $json.maturity_stage }}",
            "three_year_roi": "={{ $json.three_year_roi }}",
            "cautious_irr_pct": "={{ $json.cautious_irr_pct }}",
            "hybrid_fte_saved": "={{ $json.hybrid_fte_saved }}",
            "aggressive_irr_pct": "={{ $json.aggressive_irr_pct }}",
            "cautious_fte_saved": "={{ $json.cautious_fte_saved }}",
            "efficiency_gain_pct": "={{ $json.efficiency_gain_pct }}",
            "implementation_cost": "={{ $json.implementation_cost }}",
            "aggressive_fte_saved": "={{ $json.aggressive_fte_saved }}",
            "recommended_scenario": "={{ $json.recommended_scenario }}",
            "hybrid_annual_benefit": "={{ $json.hybrid_annual_benefit }}",
            "hybrid_payback_months": "={{ $json.hybrid_payback_months }}",
            "payback_period_months": "={{ $json.payback_period_months }}",
            "cautious_annual_benefit": "={{ $json.cautious_annual_benefit }}",
            "cautious_payback_months": "={{ $json.cautious_payback_months }}",
            "hybrid_total_investment": "={{ $json.hybrid_total_investment }}",
            "aggressive_annual_benefit": "={{ $json.aggressive_annual_benefit }}",
            "aggressive_payback_months": "={{ $json.aggressive_payback_months }}",
            "cautious_total_investment": "={{ $json.cautious_total_investment }}",
            "aggressive_total_investment": "={{ $json.aggressive_total_investment }}"
          },
          "schema": [
            {
              "id": "row_key",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "row_key",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "audit_id",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "audit_id",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "client_name",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "client_name",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "sector",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "sector",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "maturity_stage",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "maturity_stage",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "run_timestamp",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "run_timestamp",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "recommended_scenario",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "recommended_scenario",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "implementation_cost",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "implementation_cost",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "annual_saving",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "annual_saving",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "fte_saved",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "fte_saved",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "efficiency_gain_pct",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "efficiency_gain_pct",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "three_year_roi",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "three_year_roi",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "payback_period_months",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "payback_period_months",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "cautious_total_investment",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "cautious_total_investment",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "cautious_annual_benefit",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "cautious_annual_benefit",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "cautious_npv",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "cautious_npv",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "cautious_irr_pct",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "cautious_irr_pct",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "cautious_payback_months",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "cautious_payback_months",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "cautious_fte_saved",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "cautious_fte_saved",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "hybrid_total_investment",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "hybrid_total_investment",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "hybrid_annual_benefit",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "hybrid_annual_benefit",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "hybrid_npv",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "hybrid_npv",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "hybrid_irr_pct",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "hybrid_irr_pct",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "hybrid_payback_months",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "hybrid_payback_months",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "hybrid_fte_saved",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "hybrid_fte_saved",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "aggressive_total_investment",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "aggressive_total_investment",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "aggressive_annual_benefit",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "aggressive_annual_benefit",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "aggressive_npv",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "aggressive_npv",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "aggressive_irr_pct",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "aggressive_irr_pct",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "aggressive_payback_months",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "aggressive_payback_months",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "aggressive_fte_saved",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "aggressive_fte_saved",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "created_at",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "created_at",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            }
          ],
          "mappingMode": "defineBelow",
          "matchingColumns": [
            "row_key"
          ],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        },
        "options": {},
        "operation": "YOUR_BASE_ID",
        "sheetName": {
          "__rl": true,
          "mode": "name",
          "value": "Client_Models"
        },
        "documentId": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $('Set Client Config').first().json.master_sheet_id }}"
        }
      },
      "executeOnce": true,
      "typeVersion": 4.5
    },
    {
      "id": "21bce3ec-ebca-4520-979f-377331b0b897",
      "name": "Extract New RACI",
      "type": "n8n-nodes-base.code",
      "position": [
        2540,
        2960
      ],
      "parameters": {
        "jsCode": "const auditId = $('2.1 Data Cleaner').first().json.audit_id;\nconst blueprintRaw = $('3.1 Generate Target Operating Model').first().json.message.content;\n\nlet blueprint;\ntry {\nblueprint = JSON.parse(blueprintRaw);\n} catch (e) {\nreturn [\n{\njson: {\nrow_key: auditId + '|parse_error',\naudit_id: auditId,\nprocess: 'parse_error',\nresponsible: '',\naccountable: '',\nconsulted: '',\ninformed: '',\nautomation_level: '',\ntools_used: '',\n},\n},\n];\n}\n\nconst raci =\nArray.isArray(blueprint.new_raci_matrix) ? blueprint.new_raci_matrix :\nArray.isArray(blueprint.new_raci) ? blueprint.new_raci :\nArray.isArray(blueprint.raci_matrix) ? blueprint.raci_matrix :\nArray.isArray(blueprint.raci) ? blueprint.raci :\n[];\n\nconst toCsvString = (v) => {\nif (Array.isArray(v)) return v.filter(Boolean).join(', ');\nif (v === null || v === undefined) return '';\nreturn String(v);\n};\n\nreturn raci.map((r, idx) => {\nconst processCandidate =\nr.process ??\nr.Process ??\nr.process_name ??\nr.processName ??\nr.process_title ??\nr.processTitle ??\nr.name ??\nr.Name ??\nr.activity ??\nr.Activity ??\nr.workflow ??\nr.Workflow ??\nr['Process'] ??\nr['Process Name'] ??\nr['Process_Name'] ??\nr['process_name'] ??\nr['process'] ??\n'unknown_process';\n\nconst process =\nprocessCandidate === 'unknown_process'\n? ('process_' + (idx + 1))\n: String(processCandidate);\n\nconst responsible = toCsvString(r.Responsible ?? r.responsible ?? r.R ?? r['R']);\nconst accountable = toCsvString(r.Accountable ?? r.accountable ?? r.A ?? r['A']);\nconst consulted = toCsvString(r.Consulted ?? r.consulted ?? r.C ?? r['C']);\nconst informed = toCsvString(r.Informed ?? r.informed ?? r.I ?? r['I']);\n\nconst tools_used = toCsvString(r.tools_used ?? r['Tools Used'] ?? r.tools ?? r['tools']);\nconst automation_level = toCsvString(r.automation_level ?? r['Automation Level'] ?? r.automation ?? r['automation']);\n\nreturn {\njson: {\nrow_key: auditId + '|' + process,\naudit_id: auditId,\nprocess,\nresponsible,\naccountable,\nconsulted,\ninformed,\nautomation_level,\ntools_used,\n},\n};\n});"
      },
      "typeVersion": 2
    },
    {
      "id": "3c20eef7-b6e2-4f7c-9b2c-f543fefcd629",
      "name": "Write New RACI to Sheet",
      "type": "n8n-nodes-base.googleSheets",
      "position": [
        1300,
        3210
      ],
      "parameters": {
        "columns": {
          "value": {
            "process": "={{ $json.process ?? '' }}",
            "row_key": "={{ $json.row_key }}",
            "audit_id": "={{ $json.audit_id }}",
            "informed": "={{ $json.informed ?? '' }}",
            "consulted": "={{ $json.consulted ?? '' }}",
            "tools_used": "={{ $json.tools_used ?? '' }}",
            "accountable": "={{ $json.accountable ?? '' }}",
            "responsible": "={{ $json.responsible ?? '' }}",
            "automation_level": "={{ $json.automation_level ?? '' }}"
          },
          "schema": [
            {
              "id": "row_key",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "row_key",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "process",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "process",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "audit_id",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "audit_id",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "responsible",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "responsible",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "accountable",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "accountable",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "consulted",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "consulted",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "tools_used",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "tools_used",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "automation_level",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "automation_level",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "informed",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "informed",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "notes",
              "type": "string",
              "display": true,
              "removed": true,
              "required": false,
              "displayName": "notes",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            }
          ],
          "mappingMode": "defineBelow",
          "matchingColumns": [
            "row_key"
          ],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        },
        "options": {},
        "operation": "YOUR_BASE_ID",
        "sheetName": {
          "__rl": true,
          "mode": "name",
          "value": "RACI_Output.csv"
        },
        "documentId": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $('Set Client Config').first().json.master_sheet_id }}"
        }
      },
      "executeOnce": false,
      "typeVersion": 4.7
    },
    {
      "id": "321fb3c0-cbe7-4b4d-a4ab-44606f61fbdc",
      "name": "Extract KPI Updates",
      "type": "n8n-nodes-base.code",
      "position": [
        990,
        3210
      ],
      "parameters": {
        "jsCode": "const safeNodeJson = (nodeName) => {\ntry {\nif ($(nodeName).isExecuted) return $(nodeName).first().json\n} catch (e) {}\nreturn null\n}\n\nconst roiData =\nsafeNodeJson(\"3.2 Financial Model Deep-Dive\") ||\n$input.first().json ||\n{}\n\nconst blueprint =\nsafeNodeJson(\"3.1 Generate Target Operating Model\") ||\nsafeNodeJson(\"3.1 Blueprint Generator - GPT-4.1mini\") ||\n{}\n\nconst clientConfig =\nsafeNodeJson(\"Set Client Config\") ||\nsafeNodeJson(\"Optional - Map Queue Row to Config\") ||\n{}\n\nconst clientName = clientConfig.client_name || roiData.client_name || \"Unknown Client\"\nconst sector = clientConfig.sector || roiData.sector || \"\"\nconst auditId = roiData.audit_id || clientConfig.audit_id || \"\"\n\nconst getText = (obj) => {\nif (!obj) return \"\"\nif (typeof obj === \"string\") return obj\nif (obj.message && typeof obj.message.content === \"string\") return obj.message.content\nif (typeof obj.content === \"string\") return obj.content\nreturn \"\"\n}\n\nconst blueprintText = getText(blueprint)\n\nconst pickNumber = (v) => {\nconst n = Number(v)\nreturn Number.isFinite(n) ? n : null\n}\n\nconst hybrid = roiData.scenario_comparison?.hybrid || {}\nconst cautious = roiData.scenario_comparison?.cautious || {}\nconst aggressive = roiData.scenario_comparison?.aggressive || {}\n\nconst kpiUpdates = {\nclient_name: clientName,\nsector,\naudit_id: auditId,\ntimestamp: new Date().toISOString(),\nscenario_recommended: \"Hybrid\",\nscenarios: {\ncautious: {\ninvestment: pickNumber(cautious.investment),\nannual_benefit: pickNumber(cautious.annual_benefit),\nnpv: pickNumber(cautious.npv),\nirr: pickNumber(cautious.irr),\npayback_months: pickNumber(cautious.payback_months),\nfive_year_roi: pickNumber(cautious.five_year_roi),\nfte_saved: pickNumber(cautious.fte_saved)\n},\nhybrid: {\ninvestment: pickNumber(hybrid.investment),\nannual_benefit: pickNumber(hybrid.annual_benefit),\nnpv: pickNumber(hybrid.npv),\nirr: pickNumber(hybrid.irr),\npayback_months: pickNumber(hybrid.payback_months),\nfive_year_roi: pickNumber(hybrid.five_year_roi),\nfte_saved: pickNumber(hybrid.fte_saved)\n},\naggressive: {\ninvestment: pickNumber(aggressive.investment),\nannual_benefit: pickNumber(aggressive.annual_benefit),\nnpv: pickNumber(aggressive.npv),\nirr: pickNumber(aggressive.irr),\npayback_months: pickNumber(aggressive.payback_months),\nfive_year_roi: pickNumber(aggressive.five_year_roi),\nfte_saved: pickNumber(aggressive.fte_saved)\n}\n},\nblueprint_available: blueprintText.length > 0\n}\n\nreturn [{ json: kpiUpdates }]"
      },
      "typeVersion": 2
    },
    {
      "id": "f104b6e5-b68c-4009-aacf-8a3181592849",
      "name": "Generate Professional Report",
      "type": "n8n-nodes-base.code",
      "position": [
        3800,
        2960
      ],
      "parameters": {
        "jsCode": "// Generate a plain-text report file (binary) combining Executive Summary + Mermaid Diagrams.\n// Designed to work even when 'Set Client Config' is disabled.\n\nconst execSummary = $('3.4 Generate Executive Transformation Report').first().json.message?.content || '';\nconst auditId =\n  $('2.1 Data Cleaner').first().json.audit_id ||\n  $('Industry Template Selector').first().json.audit_id ||\n  $json.audit_id ||\n  `AUDIT_${Date.now()}`;\n\nconst clientName =\n  $('Industry Template Selector').first().json.client_name ||\n  $('2.1 Data Cleaner').first().json.client_name ||\n  $json.client_name ||\n  'Unknown Client';\n\n// Mermaid diagrams (optional)\nlet diagramsMarkdown = '';\ntry {\n  const diagrams = $('3.3a Mermaid Diagram Generator').first().json;\n  if (diagrams && (diagrams.markdown_report || diagrams.mermaid_markdown)) {\n    diagramsMarkdown = diagrams.markdown_report || diagrams.mermaid_markdown;\n  }\n} catch (e) {}\n\nif (!diagramsMarkdown) {\n  diagramsMarkdown = '## Mermaid Diagrams\\n\\n*Diagrams not available*\\n';\n}\n\nconst content = `${clientName} - AI Operating Model Transformation\nExecutive Summary & Transformation Roadmap\nGenerated: ${new Date().toLocaleString()}\nAudit ID: ${auditId}\n\n${'='.repeat(80)}\n\n${execSummary}\n\n${'='.repeat(80)}\n\n${diagramsMarkdown}\n\n${'='.repeat(80)}\n\nConfidential | Internal Simulation Output\nPowered by n8n\n`;\n\nreturn [{\n  json: {\n    client_name: clientName,\n    audit_id: auditId,\n    report_text: content,\n    has_diagrams: diagramsMarkdown.length > 50\n  },\n  binary: {\n    data: {\n      data: Buffer.from(content, 'utf8').toString('base64'),\n      mimeType: 'text/plain',\n      fileName: `${clientName.replace(/[^a-z0-9]+/gi,'_')}_AI_Operating_Model_${auditId}.txt`\n    }\n  }\n}];\n"
      },
      "typeVersion": 2
    },
    {
      "id": "d2a5309f-da81-4a88-8628-692967a141fc",
      "name": "Upload file",
      "type": "n8n-nodes-base.googleDrive",
      "position": [
        4110,
        2960
      ],
      "parameters": {
        "name": "={{ $json.binary.data.fileName }}",
        "driveId": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $('Set Client Config').first().json.output_drive_folder_id }}"
        },
        "options": {},
        "folderId": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $('Set Client Config').first().json.output_drive_folder_id }}"
        }
      },
      "typeVersion": 3
    },
    {
      "id": "5d63e4d9-e457-4eda-94e7-6b0d581f052c",
      "name": "4.1b Write Recommendations to Google Sheets",
      "type": "n8n-nodes-base.googleSheets",
      "position": [
        4110,
        3460
      ],
      "parameters": {
        "columns": {
          "value": {
            " AI_Fit": "={{ $json.AI_Fit }}",
            "Process": "={{ $json.Process }}",
            "row_key": "={{ $json.row_key }}",
            "Audit_ID": "={{ $json.Audit_ID }}",
            "Complexity": "={{ $json.Complexity }}",
            "ROI_Months": "={{ $json.ROI_Months }}",
            "Description": "={{ $json.Description }}",
            "Client_Name  ": "={{ $json.Client_Name }}",
            "Recommended_Tech": "={{ $json.Recommended_Tech }}",
            "Potential_Saving_Pct": "={{ $json.Potential_Saving_Pct }}"
          },
          "schema": [
            {
              "id": "row_key",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "row_key",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Audit_ID",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "Audit_ID",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Client_Name  ",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "Client_Name  ",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Process",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "Process",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": " AI_Fit",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": " AI_Fit",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Recommended_Tech",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "Recommended_Tech",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Complexity",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "Complexity",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Potential_Saving_Pct",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "Potential_Saving_Pct",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "ROI_Months",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "ROI_Months",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Description",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "Description",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            }
          ],
          "mappingMode": "defineBelow",
          "matchingColumns": [
            "row_key"
          ],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        },
        "options": {},
        "operation": "YOUR_BASE_ID",
        "sheetName": {
          "__rl": true,
          "mode": "name",
          "value": "Recommendations"
        },
        "documentId": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $('Set Client Config').first().json.master_sheet_id }}"
        }
      },
      "executeOnce": true,
      "typeVersion": 4.5
    },
    {
      "id": "3fb11b7a-c864-40f3-8248-85dfdc271564",
      "name": "Extract Recommendations Data",
      "type": "n8n-nodes-base.code",
      "position": [
        4420,
        2960
      ],
      "parameters": {
        "jsCode": "// Extract Recommendations from AI Fit Mapper (stable, no hard dependency)\n// Safe parsing + safe fallbacks + no required node execution order\n\nfunction parseAIResponse(content) {\n  if (!content) return { recommendations: [] };\n\n  let cleaned = content.trim();\n\n  if (cleaned.startsWith('```json')) cleaned = cleaned.slice(7);\n  else if (cleaned.startsWith('```')) cleaned = cleaned.slice(3);\n\n  if (cleaned.endsWith('```')) cleaned = cleaned.slice(0, -3);\n\n  cleaned = cleaned.trim();\n\n  try {\n    return JSON.parse(cleaned);\n  } catch (e) {\n    return { recommendations: [] };\n  }\n}\n\nconst base = $input.first()?.json || {};\nlet recommendationsData = { recommendations: [] };\n\n// Safe AI Fit Mapper read\ntry {\n  if ($(\"2.3 Map AI and Automation Opportunities\").isExecuted) {\n    const nodeData = $(\"2.3 Map AI and Automation Opportunities\").first().json;\n    const content = nodeData.message?.content || '';\n    recommendationsData = parseAIResponse(content);\n  }\n} catch (e) {}\n\n// Safe client + audit resolution (no hard dependency)\nlet clientConfig = { ...base };\n\ntry {\n  if ($(\"Optional - Map Queue Row to Config\").isExecuted) {\n    clientConfig = {\n      ...clientConfig,\n      ...$(\"Optional - Map Queue Row to Config\").first().json\n    };\n  }\n} catch (e) {}\n\ntry {\n  if ($(\"Set Client Config\").isExecuted) {\n    clientConfig = {\n      ...clientConfig,\n      ...$(\"Set Client Config\").first().json\n    };\n  }\n} catch (e) {}\n\nlet auditData = { ...base };\ntry {\n  if ($(\"2.1 Data Cleaner\").isExecuted) {\n    auditData = {\n      ...auditData,\n      ...$(\"2.1 Data Cleaner\").first().json\n    };\n  }\n} catch (e) {}\n\nconst clientName =\n  clientConfig.client_name ||\n  auditData.client_name ||\n  base.client_name ||\n  \"Unknown Client\";\n\nconst auditId =\n  clientConfig.audit_id ||\n  auditData.audit_id ||\n  base.audit_id ||\n  \"N/A\";\n\nconst recommendations = recommendationsData.recommendations || [];\n\nif (recommendations.length === 0) {\n  return [{\n    json: {\n      Audit_ID: auditId,\n      Client_Name: clientName,\n      Process: \"No recommendations generated\",\n      AI_Fit: \"N/A\",\n      Recommended_Tech: \"N/A\",\n      Complexity: \"N/A\",\n      Potential_Saving_Pct: 0,\n      ROI_Months: 0,\n      Description: \"AI output did not contain structured recommendations\"\n    }\n  }];\n}\n\n// Format for Google Sheets\nconst formattedRecommendations = recommendations.map(rec => ({\n  Audit_ID: auditId,\n  Client_Name: clientName,\n  Process: rec.process || \"\",\n  AI_Fit: rec.ai_fit || \"Medium\",\n  Recommended_Tech: Array.isArray(rec.recommended_tech)\n    ? rec.recommended_tech.join(\", \")\n    : rec.recommended_tech || \"\",\n  Complexity: rec.implementation_complexity || \"Moderate\",\n  Potential_Saving_Pct: Number(rec.potential_saving_pct) || 0,\n  ROI_Months: Number(rec.estimated_roi_months) || 12,\n  Description: rec.description || \"\"\n}));\n\nreturn formattedRecommendations.map(r => ({ json: r }));"
      },
      "typeVersion": 2
    },
    {
      "id": "7df4cd7a-e44f-42b5-8a3d-c5ef85aada51",
      "name": "1.3 Google Sheets - Tools Inventory",
      "type": "n8n-nodes-base.googleSheets",
      "position": [
        3310,
        760
      ],
      "parameters": {
        "options": {},
        "sheetName": {
          "__rl": true,
          "mode": "name",
          "value": "Tools_Inventory"
        },
        "documentId": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $('Set Client Config').first().json.master_sheet_id }}"
        }
      },
      "typeVersion": 4.5
    },
    {
      "id": "fd494bb0-9d3d-438d-970b-4ecf933a663a",
      "name": "3.5 Consultant Rationale Generator",
      "type": "@n8n/n8n-nodes-langchain.openAi",
      "position": [
        1300,
        3460
      ],
      "parameters": {
        "modelId": {
          "__rl": true,
          "mode": "list",
          "value": "gpt-4.1-mini",
          "cachedResultName": "GPT-4.1-MINI"
        },
        "options": {
          "maxTokens": 3000,
          "temperature": 0.4
        },
        "messages": {
          "values": [
            {
              "content": "=You are an expert AI strategy consultant reviewing an AI Operating Model audit. Generate a CONSULTANT RATIONALE document that explains the reasoning behind the recommendations.\n\nClient: {{ $('Optional - Map Queue Row to Config').first().json.client_name }}\nSector: {{ $('Optional - Map Queue Row to Config').first().json.sector }}\n\nEXECUTIVE SUMMARY:\n{{ $if($('3.4 Generate Executive Transformation Report').isExecuted, $('3.4 Generate Executive Transformation Report').first().json.message.content, 'EXEC SUMMARY NOT AVAILABLE. Node not executed.') }}\n\nFINANCIAL MODEL:\n{{ $if($('3.2 Financial Model Deep-Dive').isExecuted, JSON.stringify($('3.2 Financial Model Deep-Dive').first().json, null, 2), '{}' ) }}\n\nSUPPORTING ANALYSIS (OPTIONAL):\nInefficiencies:\n{{ $if($('2.2 Analyse Inefficiencies With OpenAI').isExecuted, $('2.2 Analyse Inefficiencies With OpenAI').first().json.message.content, '') }}\n\nRecommendations:\n{{ $if($('2.3 Map AI and Automation Opportunities').isExecuted, $('2.3 Map AI and Automation Opportunities').first().json.message.content, '') }}\n\nBlueprint:\n{{ $if($('3.1 Generate Target Operating Model').isExecuted, $('3.1 Generate Target Operating Model').first().json.message.content, '') }}\n\nGenerate a structured rationale document with these sections:\n\n1. ANALYSIS METHODOLOGY\n\nData sources used and their reliability\n\nAssumptions made during analysis\n\nLimitations of the current assessment\n\n2. KEY RECOMMENDATIONS RATIONALE\n\nFor each major recommendation, explain:\n\nWHY this was prioritized (business impact, feasibility, risk)\n\nAlternative approaches considered and why they were rejected\n\nDependencies and prerequisites\n\n3. FINANCIAL ASSUMPTIONS\n\nCost estimation methodology\n\nSavings projection basis\n\nRisk factors applied to ROI calculations\n\nSensitivity analysis notes\n\n4. DATA QUALITY NOTES\n\nGaps in client data that affected analysis\n\nAreas where consultant should probe deeper\n\nInformation that would improve accuracy\n\n5. IMPLEMENTATION RISKS\n\nTechnical risks and mitigations\n\nOrganizational change risks\n\nResource or capability gaps identified\n\n6. CONSULTANT TALKING POINTS\n\nKey messages to emphasize with client\n\nPotential client objections and responses\n\nUpsell opportunities for deeper engagement\n\n7. AREAS FOR MANUAL REVIEW\n\nSections that need human validation\n\nIndustry-specific nuances AI may have missed\n\nRecommendations that need client context\n\nWrite in a professional but direct style. This is an internal document for the consulting team, not the client."
            }
          ]
        }
      },
      "typeVersion": 1.7
    },
    {
      "id": "3bcfbea6-60c3-4c74-9b8e-09671455fc07",
      "name": "Write Rationale to Sheet",
      "type": "n8n-nodes-base.googleSheets",
      "position": [
        1920,
        3460
      ],
      "parameters": {
        "columns": {
          "value": {
            "row_key": "={{ $json.row_key }}",
            "audit_id": "={{ $json.audit_id }}",
            "created_at": "={{ $json.created_at }}",
            "client_name": "={{ $json.client_name }}",
            "assumptions_md": "={{ $json.assumptions_md }}",
            "limitations_md": "={{ $json.limitations_md }}",
            "human_review_flags_md": "={{ $json.human_review_flags_md }}",
            "human_review_required": "={{ $json.human_review_required }}",
            "consultant_rationale_text": "={{ $json.consultant_rationale_text }}"
          },
          "schema": [
            {
              "id": "row_key",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "row_key",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "audit_id",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "audit_id",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "client_name",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "client_name",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "consultant_rationale_text",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "consultant_rationale_text",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "assumptions_md",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "assumptions_md",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "limitations_md",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "limitations_md",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "human_review_flags_md",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "human_review_flags_md",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "created_at",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "created_at",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            }
          ],
          "mappingMode": "defineBelow",
          "matchingColumns": [
            "row_key"
          ],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        },
        "options": {},
        "operation": "YOUR_BASE_ID",
        "sheetName": {
          "__rl": true,
          "mode": "name",
          "value": "Consultant_Rationale.csv"
        },
        "documentId": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $('Set Client Config').first().json.master_sheet_id }}"
        }
      },
      "executeOnce": true,
      "typeVersion": 4.5
    },
    {
      "id": "2fb0f967-49cd-40c4-ae1f-d7f6304a410d",
      "name": "Optional - Watch Client Queue",
      "type": "n8n-nodes-base.googleSheetsTrigger",
      "disabled": true,
      "position": [
        990,
        1010
      ],
      "parameters": {
        "event": "=rowAdded",
        "options": {},
        "pollTimes": {
          "item": [
            {
              "mode": "everyHour"
            }
          ]
        },
        "sheetName": {
          "__rl": true,
          "mode": "name",
          "value": "Clients_Queue"
        },
        "documentId": {
          "__rl": true,
          "mode": "id",
          "value": "YOUR_MASTER_GOOGLE_SHEET_ID"
        }
      },
      "typeVersion": 1
    },
    {
      "id": "9f4838ab-69a1-4239-b70f-16cc8ad5ca23",
      "name": "Optional - Map Queue Row to Config",
      "type": "n8n-nodes-base.code",
      "disabled": true,
      "position": [
        1300,
        1010
      ],
      "parameters": {
        "jsCode": "// OPTIONAL QUEUE PATH\n// Maps a row from the optional Clients_Queue Google Sheet into the same\n// configuration contract used by the manual \"Set Client Config\" node.\n\nconst row = $input.first()?.json || {};\nconst pick = (...keys) => {\n  for (const key of keys) {\n    const value = row[key];\n    if (value !== undefined && value !== null && String(value).trim() !== '') return value;\n  }\n  return null;\n};\n\nconst clientName = pick('client_name', 'Client Name') || 'Example Organisation';\nconst compact = new Date().toISOString().replace(/[:.]/g, '').slice(0, 15);\nconst clientId = String(clientName).replace(/\\s+/g, '_').replace(/[^A-Za-z0-9_]/g, '').slice(0, 40) || 'CLIENT';\n\nreturn [{\n  json: {\n    client_name: clientName,\n    notification_email: pick('notification_email', 'Notification Email') || 'YOUR_NOTIFICATION_EMAIL',\n    sector: pick('sector', 'Sector') || 'Marketing & Creative Production',\n    maturity_stage: pick('maturity_stage', 'Maturity Stage') || 'Walk',\n    market_count: Number(pick('market_count', 'Market Count') || 5),\n\n    org_drive_file_id: pick('org_drive_file_id', 'Org Drive File ID') || 'YOUR_ORG_DOCUMENT_FILE_ID',\n    master_sheet_id: pick('master_sheet_id', 'Master Sheet ID') || 'YOUR_MASTER_GOOGLE_SHEET_ID',\n    output_drive_folder_id: pick('output_drive_folder_id', 'Output Drive Folder ID') || 'YOUR_OUTPUT_DRIVE_FOLDER_ID',\n    slack_channel_id: pick('slack_channel_id', 'Slack Channel ID') || 'YOUR_SLACK_CHANNEL_ID',\n\n    avg_fte_cost: Number(pick('avg_fte_cost') || 85000),\n    hours_per_fte_year: Number(pick('hours_per_fte_year') || 1800),\n    software_license_annual: Number(pick('software_license_annual') || 25000),\n    integration_cost_per_system: Number(pick('integration_cost_per_system') || 15000),\n    training_cost_per_fte: Number(pick('training_cost_per_fte') || 2500),\n    change_management_pct: Number(pick('change_management_pct') || 0.15),\n    discount_rate: Number(pick('discount_rate') || 0.10),\n    implementation_risk_buffer: Number(pick('implementation_risk_buffer') || 0.20),\n    benefit_realization_factor: Number(pick('benefit_realization_factor') || 0.85),\n    analysis_years: Number(pick('analysis_years') || 5),\n\n    adkar_awareness: Number(pick('adkar_awareness') || 5),\n    adkar_desire: Number(pick('adkar_desire') || 5),\n    adkar_knowledge: Number(pick('adkar_knowledge') || 5),\n    adkar_ability: Number(pick('adkar_ability') || 5),\n    adkar_reinforcement: Number(pick('adkar_reinforcement') || 5),\n    stakeholders_json: pick('stakeholders_json') || '[]',\n\n    audit_id: pick('audit_id', 'Audit ID') || `AUDIT_${clientId}_${compact}`,\n    audit_timestamp: new Date().toISOString(),\n    trigger_source: 'google_sheets_queue'\n  }\n}];"
      },
      "typeVersion": 2
    },
    {
      "id": "6d136d32-0ab4-4a6d-a0cd-b026a217a1c7",
      "name": "Optional - Mark Queue Processing",
      "type": "n8n-nodes-base.googleSheets",
      "disabled": true,
      "position": [
        1610,
        1010
      ],
      "parameters": {
        "columns": {
          "value": {
            "sector": "={{ $json.sector }}",
            "Audit_ID": "={{ $json.audit_id }}",
            "client_name": "={{ $json.client_name }}",
            "client_email": "={{ $json.client_email }}",
            "market_count": "={{ $json.market_count }}",
            "maturity_stage": "={{ $json.maturity_stage }}",
            "gdrive_folder_id": "={{ $json.gdrive_folder_id }}"
          },
          "schema": [
            {
              "id": "client_name",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "client_name",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "client_email",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "client_email",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "sector",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "sector",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "market_count",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "market_count",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "maturity_stage",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "maturity_stage",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "gdrive_folder_id",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "gdrive_folder_id",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Status",
              "type": "string",
              "display": true,
              "removed": true,
              "required": false,
              "displayName": "Status",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Started_At",
              "type": "string",
              "display": true,
              "removed": true,
              "required": false,
              "displayName": "Started_At",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Completed_At",
              "type": "string",
              "display": true,
              "removed": true,
              "required": false,
              "displayName": "Completed_At",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Audit_ID",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "Audit_ID",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "row_number",
              "type": "number",
              "display": true,
              "removed": true,
              "readOnly": true,
              "required": false,
              "displayName": "row_number",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            }
          ],
          "mappingMode": "defineBelow",
          "matchingColumns": [
            "client_name"
          ],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        },
        "options": {},
        "operation": "update",
        "sheetName": {
          "__rl": true,
          "mode": "name",
          "value": "Clients_Queue"
        },
        "documentId": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $('Set Client Config').first().json.master_sheet_id }}"
        }
      },
      "typeVersion": 4.5
    },
    {
      "id": "69f26886-9630-406a-8950-838e7f07682d",
      "name": "Optional - Mark Queue Complete",
      "type": "n8n-nodes-base.googleSheets",
      "disabled": true,
      "position": [
        7210,
        2960
      ],
      "parameters": {
        "columns": {
          "value": {
            "sector": "={{ $json.sector }}",
            "client_name": "={{ $json.client_name }}"
          },
          "schema": [
            {
              "id": "client_name",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "client_name",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "client_email",
              "type": "string",
              "display": true,
              "removed": true,
              "required": false,
              "displayName": "client_email",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "sector",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "sector",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "market_count",
              "type": "string",
              "display": true,
              "removed": true,
              "required": false,
              "displayName": "market_count",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "maturity_stage",
              "type": "string",
              "display": true,
              "removed": true,
              "required": false,
              "displayName": "maturity_stage",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "gdrive_folder_id",
              "type": "string",
              "display": true,
              "removed": true,
              "required": false,
              "displayName": "gdrive_folder_id",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Status",
              "type": "string",
              "display": true,
              "removed": true,
              "required": false,
              "displayName": "Status",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Started_At",
              "type": "string",
              "display": true,
              "removed": true,
              "required": false,
              "displayName": "Started_At",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Completed_At",
              "type": "string",
              "display": true,
              "removed": true,
              "required": false,
              "displayName": "Completed_At",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Audit_ID",
              "type": "string",
              "display": true,
              "removed": true,
              "required": false,
              "displayName": "Audit_ID",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "row_number",
              "type": "number",
              "display": true,
              "removed": true,
              "readOnly": true,
              "required": false,
              "displayName": "row_number",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            }
          ],
          "mappingMode": "defineBelow",
          "matchingColumns": [
            "client_name"
          ],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        },
        "options": {},
        "operation": "update",
        "sheetName": {
          "__rl": true,
          "mode": "name",
          "value": "Clients_Queue"
        },
        "documentId": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $('Set Client Config').first().json.master_sheet_id }}"
        }
      },
      "typeVersion": 4.5
    },
    {
      "id": "8999d8c0-b38b-46ff-b8c4-2daa2811d776",
      "name": "Industry Template Selector",
      "type": "n8n-nodes-base.code",
      "position": [
        1610,
        760
      ],
      "parameters": {
        "jsCode": "// Community-safe Industry Guidance Selector\n// This node provides qualitative sector guidance only.\n// Quantitative benchmark values must come from the user's \"Benchmarks\" sheet.\n\nconst cfg = $input.first().json || {};\nconst sector = cfg.sector || 'Marketing & Creative Production';\n\nconst templates = {\n  'Marketing & Creative Production': {\n    sector_code: 'MKT',\n    key_kpis: ['turnaround_time', 'utilization', 'cost_per_asset', 'error_rate', 'volume', 'client_satisfaction'],\n    common_inefficiencies: ['manual adaptation', 'review bottlenecks', 'tool fragmentation', 'manual localisation', 'asset-routing delays'],\n    ai_solutions: ['content generation and adaptation', 'translation/localisation assistance', 'brand compliance checks', 'workflow orchestration', 'asset routing'],\n    compliance: ['brand governance', 'privacy', 'accessibility'],\n    analysis_context: 'Focus on production efficiency, asset lifecycle, review and approval, localisation, and team utilisation.'\n  },\n  'Retail': {\n    sector_code: 'RTL',\n    key_kpis: ['inventory_turnover', 'fulfilment_time', 'return_rate', 'conversion', 'supply_chain_efficiency'],\n    common_inefficiencies: ['manual inventory updates', 'channel fragmentation', 'pricing updates', 'returns processing', 'forecasting gaps'],\n    ai_solutions: ['demand forecasting', 'inventory optimisation', 'dynamic pricing support', 'customer service automation', 'personalisation'],\n    compliance: ['privacy', 'payment security', 'consumer protection'],\n    analysis_context: 'Focus on omnichannel operations, inventory, fulfilment, customer service and supply-chain visibility.'\n  },\n  'Financial Services': {\n    sector_code: 'FIN',\n    key_kpis: ['processing_time', 'straight_through_processing', 'error_rate', 'compliance_rate', 'cost_per_case'],\n    common_inefficiencies: ['manual document processing', 'compliance bottlenecks', 'legacy integration', 'manual review', 'slow onboarding'],\n    ai_solutions: ['document processing', 'risk triage', 'fraud detection support', 'workflow orchestration', 'regulatory reporting automation'],\n    compliance: ['privacy', 'financial regulation', 'auditability', 'model governance'],\n    analysis_context: 'Focus on controls, audit trails, risk, document-heavy processes and straight-through processing.'\n  },\n  'Healthcare': {\n    sector_code: 'HLC',\n    key_kpis: ['throughput', 'documentation_time', 'error_rate', 'claims_time', 'service_quality'],\n    common_inefficiencies: ['manual documentation', 'system fragmentation', 'claims processing', 'scheduling', 'paper-based workflows'],\n    ai_solutions: ['documentation assistance', 'workflow orchestration', 'scheduling support', 'claims automation', 'knowledge retrieval'],\n    compliance: ['privacy', 'clinical safety', 'auditability', 'human oversight'],\n    analysis_context: 'Focus on safe workflow improvement, documentation, scheduling, interoperability and human review.'\n  },\n  'Manufacturing': {\n    sector_code: 'MFG',\n    key_kpis: ['oee', 'defect_rate', 'cycle_time', 'downtime', 'lead_time'],\n    common_inefficiencies: ['reactive maintenance', 'manual inspection', 'planning gaps', 'paper work instructions', 'supply-chain visibility'],\n    ai_solutions: ['predictive maintenance', 'vision-assisted quality checks', 'planning support', 'workflow orchestration', 'knowledge assistance'],\n    compliance: ['quality', 'safety', 'environmental controls', 'traceability'],\n    analysis_context: 'Focus on production flow, maintenance, quality, planning, traceability and safe automation.'\n  },\n  'Technology': {\n    sector_code: 'TECH',\n    key_kpis: ['deployment_frequency', 'lead_time', 'mttr', 'change_failure_rate', 'support_resolution_time'],\n    common_inefficiencies: ['manual testing', 'deployment friction', 'documentation gaps', 'support repetition', 'review bottlenecks'],\n    ai_solutions: ['coding assistance', 'testing automation', 'AIOps', 'support automation', 'documentation generation'],\n    compliance: ['security', 'privacy', 'change control', 'access governance'],\n    analysis_context: 'Focus on delivery flow, reliability, support, documentation, security and developer productivity.'\n  }\n};\n\nconst template = templates[sector] || templates['Marketing & Creative Production'];\n\nreturn [{\n  json: {\n    ...cfg,\n    sector_code: template.sector_code,\n    sector_kpis: template.key_kpis,\n    sector_inefficiencies: template.common_inefficiencies,\n    sector_ai_solutions: template.ai_solutions,\n    sector_compliance: template.compliance,\n    sector_analysis_context: template.analysis_context,\n    sector_benchmarks: {},\n    benchmark_source: 'User-provided Benchmarks sheet'\n  }\n}];"
      },
      "typeVersion": 2
    },
    {
      "id": "81b4a349-01d8-42bb-ac69-ed25ab2632dc",
      "name": "3.3a Mermaid Diagram Generator",
      "type": "n8n-nodes-base.code",
      "position": [
        1920,
        2960
      ],
      "parameters": {
        "jsCode": "// 3.3a Mermaid Diagram Generator\n// Output: 1 item with { audit_id, client_name, mermaid_code }\n\nfunction safeString(v) {\n  if (v === null || v === undefined) return \"\";\n  if (typeof v === \"string\") return v;\n  try { return JSON.stringify(v); } catch (e) { return String(v); }\n}\n\nfunction stripCodeFences(text) {\n  return text\n    .replace(/```json\\s*/gi, \"\")\n    .replace(/```mermaid\\s*/gi, \"\")\n    .replace(/```/g, \"\")\n    .trim();\n}\n\nfunction extractFirstJsonObject(text) {\n  // Attempts to locate the first valid JSON object or array in a messy string.\n  const s = text.trim();\n  if (!s) return null;\n\n  // Quick path\n  if ((s.startsWith(\"{\") && s.endsWith(\"}\")) || (s.startsWith(\"[\") && s.endsWith(\"]\"))) {\n    return s;\n  }\n\n  // Scan for balanced braces/brackets\n  const startIdx = [];\n  for (let i = 0; i < s.length; i++) {\n    const ch = s[i];\n    if (ch === \"{\" || ch === \"[\") startIdx.push(i);\n  }\n  for (const start of startIdx) {\n    const open = s[start];\n    const close = open === \"{\" ? \"}\" : \"]\";\n    let depth = 0;\n    for (let j = start; j < s.length; j++) {\n      const c = s[j];\n      if (c === open) depth++;\n      if (c === close) depth--;\n      if (depth === 0) {\n        return s.slice(start, j + 1);\n      }\n    }\n  }\n  return null;\n}\n\nfunction safeParseJson(maybeJsonText) {\n  const cleaned = stripCodeFences(safeString(maybeJsonText));\n  const candidate = extractFirstJsonObject(cleaned);\n  if (!candidate) return null;\n  try {\n    return JSON.parse(candidate);\n  } catch (e) {\n    return null;\n  }\n}\n\nfunction sanitizeMermaid(code) {\n  const t = stripCodeFences(safeString(code));\n\n  // Remove any stray leading/trailing junk lines\n  const lines = t.split(/\\r?\\n/).map(l => l.trimEnd());\n\n  // Filter out empty leading lines\n  while (lines.length && !lines[0].trim()) lines.shift();\n  while (lines.length && !lines[lines.length - 1].trim()) lines.pop();\n\n  return lines.join(\"\\n\").trim();\n}\n\nfunction buildFallbackMermaid(auditId, clientName) {\n  const title = clientName ? clientName : \"Client\";\n  const id = auditId ? auditId : \"audit\";\n  return `\nflowchart TB\n  A[\"Intake and Brief\"] --> B[\"Triage and Validate\"]\n  B --> C[\"Design Operating Model\"]\n  C --> D[\"RACI and Governance\"]\n  D --> E[\"Outputs and Reporting\"]\n  E --> F[\"Store in Google Sheets\"]\n  subgraph Meta\n    M1[\"audit_id: ${id}\"]\n    M2[\"client_name: ${title}\"]\n  end\n`.trim();\n}\n\n// 1) Read base fields from incoming item\nconst inputItem = $input.first().json || {};\n\nconst audit_id = safeString(inputItem.audit_id || inputItem.auditId || inputItem.audit || \"\").trim();\nconst client_name = safeString(inputItem.client_name || inputItem.clientName || inputItem.client || \"\").trim();\n\n// 2) Identify model output location\n// Supports either direct field or common OpenAI message shapes\nconst rawModel =\n  inputItem.mermaid_json ||\n  inputItem.mermaid ||\n  inputItem.diagram ||\n  inputItem.message?.content ||\n  inputItem.choices?.[0]?.message?.content ||\n  inputItem.data?.[0]?.message?.content ||\n  inputItem.output ||\n  \"\";\n\n// 3) Try parse JSON that contains mermaid, else treat as mermaid text\nconst parsed = safeParseJson(rawModel);\n\n// Accepted JSON shapes:\n// { \"mermaid_code\": \"...\" }\n// { \"mermaid\": \"...\" }\n// { \"diagrams\": { \"main\": \"...\" } }\n// { \"bundle\": \"...\" }\nlet mermaid_code = \"\";\n\nif (parsed && typeof parsed === \"object\") {\n  mermaid_code =\n    safeString(parsed.mermaid_code) ||\n    safeString(parsed.mermaid) ||\n    safeString(parsed.bundle) ||\n    safeString(parsed.diagrams?.main) ||\n    \"\";\n} else {\n  mermaid_code = safeString(rawModel);\n}\n\nmermaid_code = sanitizeMermaid(mermaid_code);\n\n// 4) Ensure a single stable mermaid bundle\n// If model returned multiple diagrams, we still wrap as one bundle section.\nif (!mermaid_code) {\n  mermaid_code = buildFallbackMermaid(audit_id, client_name);\n} else {\n  // Ensure it starts with a mermaid header if it looks like raw nodes\n  const startsOk =\n    mermaid_code.startsWith(\"flowchart\") ||\n    mermaid_code.startsWith(\"sequenceDiagram\") ||\n    mermaid_code.startsWith(\"stateDiagram\") ||\n    mermaid_code.startsWith(\"erDiagram\") ||\n    mermaid_code.startsWith(\"classDiagram\") ||\n    mermaid_code.startsWith(\"journey\") ||\n    mermaid_code.startsWith(\"gantt\") ||\n    mermaid_code.startsWith(\"mindmap\");\n\n  if (!startsOk) {\n    mermaid_code = `flowchart TB\\n${mermaid_code}`;\n  }\n\n  // Add a small metadata footer as comments, stable and safe\n  const metaLines = [\n    \"\",\n    \"%% ---\",\n    `%% audit_id: ${audit_id || \"unknown\"}`,\n    `%% client_name: ${client_name || \"unknown\"}`,\n    \"%% ---\",\n  ];\n  mermaid_code = `${mermaid_code}\\n${metaLines.join(\"\\n\")}`.trim();\n}\n\n// 5) Output exactly one item for downstream sheet writes\nreturn [\n  {\n    json: {\n      audit_id: audit_id || \"unknown\",\n      client_name: client_name || \"unknown\",\n      mermaid_code,\n    },\n  },\n];"
      },
      "typeVersion": 2
    },
    {
      "id": "febfb4fe-ae33-445d-9fac-fed1b3c23c2f",
      "name": "Write Diagrams to Sheet",
      "type": "n8n-nodes-base.googleSheets",
      "position": [
        1610,
        3210
      ],
      "parameters": {
        "columns": {
          "value": {
            "row_key": "={{ $json.row_key }}",
            "audit_id": "={{ $json.audit_id }}",
            "created_at": "={{ $json.created_at }}",
            "render_hint": "={{ $json.render_hint }}",
            "diagram_type": "={{ $json.diagram_type }}",
            "mermaid_code": "={{ $json.mermaid_code }}"
          },
          "schema": [
            {
              "id": "row_key",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "row_key",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "audit_id",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "audit_id",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "diagram_type",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "diagram_type",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "mermaid_code",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "mermaid_code",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "render_hint",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "render_hint",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "created_at",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "created_at",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            }
          ],
          "mappingMode": "defineBelow",
          "matchingColumns": [
            "row_key"
          ],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        },
        "options": {},
        "operation": "YOUR_BASE_ID",
        "sheetName": {
          "__rl": true,
          "mode": "name",
          "value": "Diagrams.csv"
        },
        "documentId": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $('Set Client Config').first().json.master_sheet_id }}"
        }
      },
      "executeOnce": true,
      "typeVersion": 4.5
    },
    {
      "id": "925410d2-d32b-4d90-a74d-8eff1389479c",
      "name": "Limit to First Item (Rationale)",
      "type": "n8n-nodes-base.limit",
      "position": [
        1610,
        3460
      ],
      "parameters": {},
      "typeVersion": 1
    },
    {
      "id": "a5a6b2b7-1568-4e13-968b-a49f9720ac08",
      "name": "Limit to First Item (Notifications)",
      "type": "n8n-nodes-base.limit",
      "position": [
        5040,
        2960
      ],
      "parameters": {},
      "typeVersion": 1
    },
    {
      "id": "e7e5bf6b-393a-4565-b517-9354ed68ce5f",
      "name": "Limit to First Item (Supabase)",
      "type": "n8n-nodes-base.limit",
      "disabled": true,
      "position": [
        7520,
        2960
      ],
      "parameters": {},
      "typeVersion": 1
    },
    {
      "id": "c3944f14-fa9e-4c51-9bbb-2dae9229b9df",
      "name": "Limit to First Item (Before Executive Summary)",
      "type": "n8n-nodes-base.limit",
      "position": [
        2230,
        3210
      ],
      "parameters": {},
      "typeVersion": 1
    },
    {
      "id": "e7d23c24-5ee7-4a68-96fc-c298ee937b09",
      "name": "3.4A Prepare Executive Report Context",
      "type": "n8n-nodes-base.code",
      "position": [
        2540,
        3210
      ],
      "parameters": {
        "jsCode": "// Loop over input items and add a new field called 'myNewField' to the JSON of each one\nfor (const item of $input.all()) {\n  item.json.myNewField = 1;\n}\n\nreturn $input.all();"
      },
      "typeVersion": 2
    },
    {
      "id": "38fe5b8b-aacc-434c-94fe-4781f3cd247b",
      "name": "Parse",
      "type": "n8n-nodes-base.code",
      "position": [
        3490,
        2960
      ],
      "parameters": {
        "jsCode": "function stripFences(t) {\n  return String(t || '').replace(/```json\\s*|```/g, '').trim();\n}\n\nfunction tryParseJson(text) {\n  const cleaned = stripFences(text);\n  try { return JSON.parse(cleaned); } catch (e) { return null; }\n}\n\nfunction extractSection(md, heading) {\n  const src = String(md || '');\n  const idx = src.indexOf(heading);\n  if (idx === -1) return '';\n  const rest = src.slice(idx);\n  // stop at next \"## \" heading\n  const next = rest.slice(heading.length).search(/\\n##\\s+/);\n  if (next === -1) return rest.trim();\n  return rest.slice(0, heading.length + next).trim();\n}\n\nfunction extractTable(md, heading) {\n  const section = extractSection(md, heading);\n  const lines = section.split('\\n');\n  const tableLines = [];\n  let started = false;\n  for (const line of lines) {\n    if (line.includes('|') && line.trim().startsWith('|')) {\n      started = true;\n      tableLines.push(line);\n      continue;\n    }\n    if (started && (!line.trim() || !line.includes('|'))) break;\n  }\n  return tableLines.join('\\n').trim();\n}\n\nconst content = $json.message?.content || $json.choices?.[0]?.message?.content || '';\n\nconst parsed = tryParseJson(content);\n\nlet out = {};\n\nif (parsed && typeof parsed === 'object') {\n  out = parsed;\n} else {\n  // Fallback: store markdown and key tables as strings\n  out = {\n    executive_summary_md: content,\n    pain_points_table_md: extractTable(content, '## 2.2 Key Inefficiencies & Pain Points'),\n    agents_table_md: extractTable(content, '### 3.3 AI Agents & Automation Architecture'),\n    workflows_table_md: extractTable(content, '### 3.4 n8n Workflow Automation'),\n    raci_table_md: extractTable(content, '### 3.5 New RACI Matrix'),\n    financials_table_md: extractTable(content, '### 1.4 Expected Business Impact')\n  };\n}\n\nreturn {\n  new_roles_json: JSON.stringify(out.new_roles || []),\n  swim_lanes_json: JSON.stringify(out.swim_lanes || []),\n  governance_model_json: JSON.stringify(out.governance_model || {}),\n  tech_stack_json: JSON.stringify(out.tech_stack || {}),\n  created_at: new Date().toISOString(),\n  Recommended_Scenario: out.recommended_scenario || '',\n  Annual_Saving: out.annual_saving || '',\n  Implementation_Cost: out.implementation_cost || '',\n  FTE_Saved: out.fte_saved || '',\n  executive_summary_md: out.executive_summary_md || content,\n  pain_points_table_md: out.pain_points_table_md || '',\n  agents_table_md: out.agents_table_md || '',\n  workflows_table_md: out.workflows_table_md || '',\n  raci_table_md: out.raci_table_md || '',\n  financials_table_md: out.financials_table_md || ''\n};"
      },
      "typeVersion": 2
    },
    {
      "id": "7d057465-c2c3-41ec-851e-8099344a769c",
      "name": "2.2 Analyse Inefficiencies With OpenAI",
      "type": "@n8n/n8n-nodes-langchain.openAi",
      "position": [
        4390,
        760
      ],
      "parameters": {
        "modelId": {
          "__rl": true,
          "mode": "list",
          "value": "gpt-4.1-mini",
          "cachedResultName": "GPT-4.1-MINI"
        },
        "options": {
          "temperature": 0.3
        },
        "messages": {
          "values": [
            {
              "content": "=You are an expert operations consultant analyzing a company's operating model.\n\nClient: {{ $('Optional - Map Queue Row to Config').first().json.client_name }}\nSector: {{ $('Optional - Map Queue Row to Config').first().json.sector }}\n\nSector Context:\n{{ $if($(\"2.4b Benchmark Comparator\").isExecuted, $(\"2.4b Benchmark Comparator\").first().json.sector_analysis_context, \"\") }}\n\nINDUSTRY-SPECIFIC INEFFICIENCIES TO LOOK FOR:\n{{ $if($(\"2.4b Benchmark Comparator\").isExecuted, \"- \" + $(\"2.4b Benchmark Comparator\").first().json.sector_inefficiencies.join(\"\\n- \"), \"\") }}\n\nINDUSTRY BENCHMARKS:\n{{ $if($(\"2.4b Benchmark Comparator\").isExecuted, JSON.stringify($(\"2.4b Benchmark Comparator\").first().json.sector_benchmarks, null, 2), \"{}\") }}\n\nAnalyze the following operating model data and identify:\n\nRedundancies (duplicate tools, overlapping roles)\n\nBottlenecks (process delays, approval chains)\n\nManual dependencies (repetitive human tasks)\n\nPay special attention to inefficiencies common in the {{ $('Optional - Map Queue Row to Config').first().json.sector }} sector.\n\nFor each process identified, score it on:\n\nAutomation Readiness (1-10): How easy to automate\n\nImpact Potential (1-10): Expected efficiency gain\n\nRisk Level (1-10): Implementation complexity or risk\n\nData to analyze:\n\n{{ JSON.stringify($('2.1 Data Cleaner').first().json, null, 2) }}\n\nReturn your analysis as structured JSON only:\n{\n\"inefficiencies\": [\n{\n\"category\": \"redundancy|bottleneck|manual_dependency\",\n\"description\": \"...\",\n\"affected_process\": \"...\",\n\"automation_readiness\": 1,\n\"impact_potential\": 1,\n\"risk_level\": 1,\n\"annual_cost\": 0,\n\"industry_relevance\": \"Why this matters for {{ $('Optional - Map Queue Row to Config').first().json.sector }}\"\n}\n],\n\"summary\": \"Executive summary of key findings\",\n\"sector_specific_insights\": \"Insights specific to {{ $('Optional - Map Queue Row to Config').first().json.sector }} industry\"\n}"
            }
          ]
        }
      },
      "typeVersion": 1.7
    },
    {
      "id": "9022cbc3-ce8e-4c7d-86de-56c4fc4f0146",
      "name": "Final Payload",
      "type": "n8n-nodes-base.code",
      "position": [
        4730,
        2960
      ],
      "parameters": {
        "jsCode": "// \u2500\u2500\u2500 FINAL PAYLOAD v6 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Goals\n// 1) No undefined vars (fixes \"auditId is not defined\").\n// 2) All tab row objects match your sheet headers exactly.\n// 3) Writers read ONLY from Final Payload output ($json.<field>), not old nodes.\n// 4) KPI_Benchmarking now outputs metric rows (not scenario rows).\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nfunction safeGet(nodeName) {\n  try {\n    const n = $(nodeName);\n    return (n && n.isExecuted) ? (n.first().json || null) : null;\n  } catch (e) { return null; }\n}\nfunction safeContent(nodeName) {\n  try {\n    const n = $(nodeName);\n    if (!n || !n.isExecuted) return '';\n    const j = n.first().json;\n    return j.message?.content || j.text || j.content || j.output || '';\n  } catch (e) { return ''; }\n}\nfunction safeAll(nodeName) {\n  try {\n    const n = $(nodeName);\n    return (n && n.isExecuted) ? n.all().map(i => i.json) : [];\n  } catch (e) { return []; }\n}\nfunction firstNonEmpty(...vals) {\n  for (const v of vals) {\n    if (v !== null && v !== undefined && v !== '' && v !== '[Diagram not generated...]') return v;\n  }\n  return '';\n}\nfunction str(v) {\n  if (v === null || v === undefined) return '';\n  if (typeof v === 'string') return v;\n  if (typeof v === 'number' || typeof v === 'boolean') return String(v);\n  return '';\n}\nfunction safeNum(v) {\n  if (v === undefined || v === null) return '';\n  if (typeof v === 'string' && v.trim() === '') return '';\n  const n = Number(v);\n  return Number.isFinite(n) ? n : '';\n}\nfunction extractSection(text, ...headings) {\n  if (!text) return '';\n  for (const h of headings) {\n    const re = new RegExp('##?\\\\s+' + h + '[\\\\s\\\\S]*?(?=##|$)', 'i');\n    const m = text.match(re);\n    if (m) return m[0].replace(/^##?\\\\s+[^\\\\n]*\\\\n?/, '').trim();\n  }\n  return '';\n}\n\n// \u2500\u2500\u2500 Cross-node data (guarded) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\nconst clientCfg   = safeGet('Optional - Map Queue Row to Config') || {};\nconst triggerRow  = safeGet('Optional - Watch Client Queue') || {};\nconst dataCleaner = safeGet('2.1 Data Cleaner') || {};\nconst financial   = safeGet('3.2 Financial Model Deep-Dive') || {};\nconst upload      = safeGet('Upload file')\n                 || safeGet('Upload File')\n                 || safeGet('Upload file to Google Drive')\n                 || {};\n\nconst execSummaryText = safeContent('3.4 Generate Executive Transformation Report');\nconst rationaleText   = safeContent('3.5 Consultant Rationale Generator');\n\nconst diagramSrc  = safeGet('3.3a Mermaid Diagram Generator') || {};\n\n// If you have a node that computes these, wire it here.\n// Otherwise they will stay null until you add the values upstream.\nconst totalsSrc =\n  safeGet('2.2 Inefficiency Scorer - GPT-4MINI') ||\n  safeGet('2.2 Inefficiency Scorer') ||\n  safeGet('Totals') ||\n  {};\n\n// \u2500\u2500\u2500 Identifiers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\nconst auditId = str(firstNonEmpty(\n  clientCfg.audit_id, clientCfg.Audit_ID, clientCfg.AUDIT_ID,\n  dataCleaner.audit_id, dataCleaner.Audit_ID,\n  upload.audit_id,\n  ''\n));\nconst clientName = str(firstNonEmpty(\n  // preferred: Optional - Map Queue Row to Config\n  clientCfg.client_name, clientCfg.Client_Name, clientCfg.CLIENT_NAME,\n\n  // fallback: trigger row direct\n  triggerRow.client_name, triggerRow.Client_Name, triggerRow['Client Name'], triggerRow.client, triggerRow.Client,\n\n  // fallback: discovery outputs if available\n  dataCleaner.client_name, dataCleaner.Client_Name,\n  upload.client_name,\n));\nconst sector = str(firstNonEmpty(\n  clientCfg.sector, clientCfg.Sector,\n  dataCleaner.sector, dataCleaner.Sector,\n  ''\n));\nconst maturity = str(firstNonEmpty(\n  clientCfg.maturity_stage, clientCfg.Maturity_Stage,\n  dataCleaner.maturity_stage,\n  ''\n));\n\nconst reportUrl  = str(firstNonEmpty(upload.webViewLink, upload.url, upload.fileUrl));\nconst generatedAt = new Date().toISOString();\nconst runId = 'run_' + Date.now();\n\n// \u2500\u2500\u2500 Financial scenario convenience (kept for Client_Models) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\nconst sc  = financial.scenario_comparison || {};\nconst cau = sc.cautious   || {};\nconst hyb = sc.hybrid     || {};\nconst agg = sc.aggressive || {};\n\nconst recommendedScenario = str(firstNonEmpty(financial.recommended_scenario, 'hybrid'));\n\n// \u2500\u2500\u2500 Consultant rationale parsing \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\nconst assumptionsMd = extractSection(rationaleText, 'Assumptions?') || '';\nconst limitationsMd = extractSection(rationaleText, 'Limitations?') || '';\nconst humanReviewMd = extractSection(rationaleText, 'Human Review Required', 'Human Review Flags?', 'Human Review') || '';\n\nconst assumptionsVal   = assumptionsMd || '[No assumptions recorded]';\nconst limitationsVal   = limitationsMd || '[No limitations recorded]';\nconst humanReviewVal   = humanReviewMd || '[No human review flags recorded]';\nconst rationaleTextVal = str(rationaleText) || '[Rationale not generated]';\n\n// \u2500\u2500\u2500 Exec summary section parsing (for sheet columns) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\nconst financialTableMd = extractSection(execSummaryText, 'Financial Table', 'Financial Highlights') || '';\nconst kpiHighlightsMd  = extractSection(execSummaryText, 'KPI Highlights', 'KPIs') || '';\nconst risksMd          = extractSection(execSummaryText, 'Risks', 'Risks and Mitigations') || '';\nconst nextStepsMd      = extractSection(execSummaryText, 'Next Steps', 'Recommended Next Steps') || '';\n\nconst execSummaryVal = str(execSummaryText) || '[Executive summary not generated]';\n\n// \u2500\u2500\u2500 KPI Benchmarking metric rows (matches your headers) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Expected upstream shape per item (any node name below):\n// metric, client_value, industry_avg, best_in_class, direction, unit, gap_vs_avg_pct, status, opportunity_value\nconst kpiMetricRowsSource =\n  safeAll('Extract KPI Benchmarking Rows').length ? safeAll('Extract KPI Benchmarking Rows')\n  : safeAll('Extract KPI Updates').length ? safeAll('Extract KPI Updates')\n  : safeAll('KPI Metric Rows').length ? safeAll('KPI Metric Rows')\n  : [];\n\n// If upstream node is returning scenario-style KPI rows, hard stop them here.\nconst kpiBenchmarkingRows = kpiMetricRowsSource\n  .filter(r => (r.metric || r.kpi || r.name))  // drop empty items\n  .map((r, idx) => {\n    const metric = str(firstNonEmpty(r.metric, r.kpi, r.name));\n    const rowKey = str(firstNonEmpty(\n      r.row_key,\n      `${auditId}|kpi_benchmarking|${metric || ('row_' + idx)}`\n    ));\n\n    return {\n      row_key:           rowKey,\n      metric:            metric,\n      client_value:      safeNum(firstNonEmpty(r.client_value, r.current_value, r.value)),\n      industry_avg:      safeNum(firstNonEmpty(r.industry_avg, r.benchmark_avg, r.avg)),\n      best_in_class:     safeNum(firstNonEmpty(r.best_in_class, r.benchmark_best, r.best)),\n      direction:         str(firstNonEmpty(r.direction, r.higher_is_better ? 'higher' : '', r.lower_is_better ? 'lower' : '')),\n      unit:              str(firstNonEmpty(r.unit, r.units)),\n      gap_vs_avg_pct:    safeNum(firstNonEmpty(r.gap_vs_avg_pct, r.gap_pct, r.delta_pct)),\n      status:            str(firstNonEmpty(r.status, r.performance_status)),\n      opportunity_value: safeNum(firstNonEmpty(r.opportunity_value, r.value_opportunity)),\n    };\n  });\n\n// \u2500\u2500\u2500 Client Models row (matches your Client_Models tab columns) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\nconst clientModelsRows = [{\n  row_key:               `${auditId}|client_models`,\n  audit_id:              auditId,\n  client_name:           clientName,\n  sector:                sector,\n  maturity_stage:        maturity,\n  run_timestamp:         generatedAt,\n\n  recommended_scenario:  recommendedScenario,\n  implementation_cost:   safeNum(financial.implementation_cost),\n  annual_saving:         safeNum(financial.annual_saving),\n  fte_saved:             safeNum(financial.fte_saved),\n  efficiency_gain_pct:   safeNum(financial.efficiency_gain_pct),\n  three_year_roi:        safeNum(financial.three_year_roi),\n  payback_period_months: safeNum(financial.payback_period_months),\n\n  cautious_total_investment:   safeNum(cau.total_investment),\n  cautious_annual_benefit:     safeNum(cau.annual_benefit),\n  cautious_npv:                safeNum(cau.npv),\n  cautious_irr_pct:            safeNum(cau.irr_percentage || cau.irr_pct || cau.irr),\n  cautious_payback_months:     safeNum(cau.payback_months),\n  cautious_fte_saved:          safeNum(cau.fte_saved),\n\n  hybrid_total_investment:     safeNum(hyb.total_investment),\n  hybrid_annual_benefit:       safeNum(hyb.annual_benefit),\n  hybrid_npv:                  safeNum(hyb.npv),\n  hybrid_irr_pct:              safeNum(hyb.irr_percentage || hyb.irr_pct || hyb.irr),\n  hybrid_payback_months:       safeNum(hyb.payback_months),\n  hybrid_fte_saved:            safeNum(hyb.fte_saved),\n\n  aggressive_total_investment: safeNum(agg.total_investment),\n  aggressive_annual_benefit:   safeNum(agg.annual_benefit),\n  aggressive_npv:              safeNum(agg.npv),\n  aggressive_irr_pct:          safeNum(agg.irr_percentage || agg.irr_pct || agg.irr),\n  aggressive_payback_months:   safeNum(agg.payback_months),\n  aggressive_fte_saved:        safeNum(agg.fte_saved),\n}];\n\n// \u2500\u2500\u2500 Consultant rationale row (kept minimal; expand if your sheet has more) \u2500\u2500\nconst consultantRationaleRows = [{\n  row_key:                   `${auditId}|consultant_rationale`,\n  audit_id:                  auditId,\n  client_name:               clientName,\n  consultant_rationale_text: rationaleTextVal,\n  assumptions_md:            assumptionsVal,\n  limitations_md:            limitationsVal,\n  human_review_required:     humanReviewVal,\n  human_review_flags_md:     humanReviewVal,\n  created_at:                generatedAt,\n}];\n\n// \u2500\u2500\u2500 Diagrams row \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\nconst architectureDiagramRows = [{\n  row_key:      `${clientName}|${auditId}|architecture`,\n  audit_id:     auditId,\n  diagram_type: 'architecture',\n  mermaid_code: str(firstNonEmpty(diagramSrc.mermaid_code, '[Diagram not generated]')),\n  render_hint:  'mermaid',\n  created_at:   generatedAt,\n}];\n\n// \u2500\u2500\u2500 RACI rows (kept as-is) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\nconst raciRows = safeAll('Extract New RACI').map(row => ({\n  ...row,\n  audit_id: str(row.audit_id || auditId),\n  row_key:  str(row.row_key  || (auditId + '|' + (row.process || 'unknown_process'))),\n}));\n\n// \u2500\u2500\u2500 Recommendations rows (kept as-is) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\nconst recommendationsRows = safeAll('Extract Recommendations Data').map(row => ({\n  ...row,\n  Audit_ID:    str(row.Audit_ID    || auditId),\n  Client_Name: str(row.Client_Name || clientName),\n  row_key:     str(row.row_key || (str(row.Audit_ID || auditId) + '|' + str(row.Process || 'unknown'))),\n}));\n\n// \u2500\u2500\u2500 AUDIT_MASTER row (MATCHES YOUR HEADERS EXACTLY) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// row_key, audit_id, client_name, sector, maturity_stage, run_timestamp,\n// total_baseline_days, total_orchestrated_days, total_reduction_pct,\n// total_opportunity_value, overall_status, notes\nconst auditMasterRows = [{\n  row_key:                 `${auditId}|audit_master`,\n  audit_id:                auditId,\n  client_name:             clientName,\n  sector:                  sector,\n  maturity_stage:          maturity,\n  run_timestamp:           generatedAt,\n\n  total_baseline_days:     safeNum(firstNonEmpty(totalsSrc.total_baseline_days, totalsSrc.baseline_days)),\n  total_orchestrated_days: safeNum(firstNonEmpty(totalsSrc.total_orchestrated_days, totalsSrc.orchestrated_days)),\n  total_reduction_pct:     safeNum(firstNonEmpty(totalsSrc.total_reduction_pct, totalsSrc.reduction_pct)),\n  total_opportunity_value: safeNum(firstNonEmpty(totalsSrc.total_opportunity_value, totalsSrc.opportunity_value)),\n\n  overall_status:          'complete',\n  notes:                   '',\n}];\n\n// \u2500\u2500\u2500 EXECUTIVE_SUMMARY row (MATCHES YOUR HEADERS EXACTLY) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// row_key, audit_id, client_name, sector, maturity_stage,\n// executive_summary_text, financial_table_md, kpi_highlights_md,\n// risks_md, next_steps_md, created_at\nconst execSummaryRows = [{\n  row_key:                `${auditId}|executive_summary`,\n  audit_id:               auditId,\n  client_name:            clientName,\n  sector:                 sector,\n  maturity_stage:         maturity,\n\n  executive_summary_text: execSummaryVal,\n  financial_table_md:     financialTableMd,\n  kpi_highlights_md:      kpiHighlightsMd,\n  risks_md:               risksMd,\n  next_steps_md:          nextStepsMd,\n\n  created_at:             generatedAt,\n}];\n\n// \u2500\u2500\u2500 Email assembly (simple and deterministic) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\nconst emailSubject = `AI Operating Model Audit Complete - ${clientName || 'Unknown Client'}`;\n\nconst emailBody = [\n  `<h2>AI Operating Model Audit Complete</h2>`,\n  `<p><strong>Client:</strong> ${clientName || 'Unknown Client'}</p>`,\n  `<p><strong>Sector:</strong> ${sector || ''}</p>`,\n  `<p><strong>Maturity Stage:</strong> ${maturity || ''}</p>`,\n  `<p><strong>Audit ID:</strong> ${auditId || ''}</p>`,\n  `<p><strong>Completed At:</strong> ${generatedAt}</p>`,\n  reportUrl ? `<p><strong>Report:</strong> <a href=\"${reportUrl}\">${reportUrl}</a></p>` : '',\n  `<hr/>`,\n  `<h3>Executive Summary</h3>`,\n  `<pre style=\"white-space:pre-wrap;font-family:inherit;\">${(execSummaryVal || '').slice(0, 2500)}</pre>`,\n].filter(Boolean).join('\\n');\n\n// \u2500\u2500\u2500 Final Payload \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\nconst finalPayload = {\n  audit_id:       auditId,\n  client_name:    clientName,\n  sector:         sector,\n  maturity_stage: maturity,\n  run_id:         runId,\n  report_url:     reportUrl,\n\n  // sheet-ready arrays\n  audit_master_rows:         auditMasterRows,\n  exec_summary_rows:         execSummaryRows,\n  kpi_benchmarking_rows:     kpiBenchmarkingRows,\n\n  client_models_rows:        clientModelsRows,\n  consultant_rationale_rows: consultantRationaleRows,\n  architecture_diagram_rows: architectureDiagramRows,\n  recommendations_rows:      recommendationsRows,\n  raci_rows:                 raciRows,\n\n  // for Gmail node (use these directly)\n  email_subject: emailSubject,\n  email_body:    emailBody,\n\n  _meta: {\n    version:          'v6',\n    generated_at:     generatedAt,\n  },\n};\n\nreturn [{ json: finalPayload }];"
      },
      "executeOnce": true,
      "typeVersion": 2
    },
    {
      "id": "254d6a42-cd0b-44a9-ae63-de374f895d88",
      "name": "Limit to First Item (Notifications)1",
      "type": "n8n-nodes-base.limit",
      "position": [
        5350,
        2960
      ],
      "parameters": {},
      "typeVersion": 1
    },
    {
      "id": "7045563a-eb01-40b9-b79e-4ae4ba990fbf",
      "name": "Split Client Models Rows",
      "type": "n8n-nodes-base.splitOut",
      "position": [
        5660,
        2960
      ],
      "parameters": {
        "options": {},
        "fieldToSplitOut": "client_models_rows"
      },
      "typeVersion": 1
    },
    {
      "id": "adb8c075-6a77-4ac7-8b59-720b0b718692",
      "name": "Split Diagrams Rows",
      "type": "n8n-nodes-base.splitOut",
      "position": [
        3490,
        3210
      ],
      "parameters": {
        "options": {},
        "fieldToSplitOut": "architecture_diagram_rows"
      },
      "typeVersion": 1
    },
    {
      "id": "40664fa7-2dea-4ec5-8c1f-65585420ce5f",
      "name": "Split Recommendations Rows",
      "type": "n8n-nodes-base.splitOut",
      "disabled": true,
      "position": [
        3800,
        3210
      ],
      "parameters": {
        "options": {},
        "fieldToSplitOut": "recommendations_rows"
      },
      "typeVersion": 1
    },
    {
      "id": "14825a88-afdc-4db2-8c1c-fcce561c8f5c",
      "name": "Split RACI Rows",
      "type": "n8n-nodes-base.splitOut",
      "position": [
        4110,
        3210
      ],
      "parameters": {
        "options": {},
        "fieldToSplitOut": "raci_rows"
      },
      "typeVersion": 1
    },
    {
      "id": "e1478243-6bff-45e5-8b02-5b79cd34acb1",
      "name": "Split Rationale Rows",
      "type": "n8n-nodes-base.splitOut",
      "position": [
        4420,
        3210
      ],
      "parameters": {
        "options": {},
        "fieldToSplitOut": "consultant_rationale_rows"
      },
      "typeVersion": 1
    },
    {
      "id": "5c6b6b7f-21bd-4f9a-a329-6b9aaaf81286",
      "name": "Split Audit Master Rows",
      "type": "n8n-nodes-base.splitOut",
      "position": [
        4730,
        3210
      ],
      "parameters": {
        "options": {},
        "fieldToSplitOut": "audit_master_rows"
      },
      "typeVersion": 1
    },
    {
      "id": "fad6cdf3-9a96-4b3d-81b1-55665ae217d1",
      "name": "Split Exec Summary Rows",
      "type": "n8n-nodes-base.splitOut",
      "position": [
        5040,
        3210
      ],
      "parameters": {
        "options": {},
        "fieldToSplitOut": "exec_summary_rows"
      },
      "typeVersion": 1
    },
    {
      "id": "75dac5ee-b318-4e1f-81ad-38faacbc24e5",
      "name": "Split KPI Benchmarking Rows",
      "type": "n8n-nodes-base.splitOut",
      "position": [
        5350,
        3210
      ],
      "parameters": {
        "options": {},
        "fieldToSplitOut": "kpi_benchmarking_rows"
      },
      "typeVersion": 1
    },
    {
      "id": "ccad8f6e-35ce-4d77-a9a7-a40c1fb7c956",
      "name": "Split KPI Snapshot Rows",
      "type": "n8n-nodes-base.splitOut",
      "disabled": true,
      "position": [
        5660,
        3210
      ],
      "parameters": {
        "options": {},
        "fieldToSplitOut": "kpi_snapshot_rows"
      },
      "typeVersion": 1
    },
    {
      "id": "d12f4de7-ad12-4d0b-8211-070a74e6b5b9",
      "name": "Write Audit Master to Sheet",
      "type": "n8n-nodes-base.googleSheets",
      "position": [
        4420,
        3460
      ],
      "parameters": {
        "columns": {
          "value": {
            "sector": "={{ $json.sector }}",
            "row_key": "={{ $json.row_key }}",
            "audit_id": "={{ $json.audit_id }}",
            "client_name": "={{ $json.client_name }}",
            "maturity_stage": "={{ $json.maturity_stage }}"
          },
          "schema": [
            {
              "id": "row_key",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "row_key",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "audit_id",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "audit_id",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "client_name",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "client_name",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "sector",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "sector",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "maturity_stage",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "maturity_stage",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "run_timestamp",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "run_timestamp",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "total_baseline_days",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "total_baseline_days",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "total_orchestrated_days",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "total_orchestrated_days",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "total_reduction_pct",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "total_reduction_pct",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "total_opportunity_value",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "total_opportunity_value",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "overall_status",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "overall_status",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "notes",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "notes",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            }
          ],
          "mappingMode": "defineBelow",
          "matchingColumns": [
            "row_key"
          ],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        },
        "options": {},
        "operation": "YOUR_BASE_ID",
        "sheetName": {
          "__rl": true,
          "mode": "name",
          "value": "Audit_Master.csv"
        },
        "documentId": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $('Set Client Config').first().json.master_sheet_id }}"
        }
      },
      "executeOnce": false,
      "typeVersion": 4.5
    },
    {
      "id": "d2e4778b-90b7-44c1-9683-93bccc2eb9d6",
      "name": "Write Exec Summary to Sheet",
      "type": "n8n-nodes-base.googleSheets",
      "position": [
        4730,
        3460
      ],
      "parameters": {
        "columns": {
          "value": {
            "sector": "={{ $json.sector }}",
            "row_key": "={{ $json.row_key }}",
            "audit_id": "={{ $json.audit_id }}",
            "risks_md": "={{ $json.risks_md }}",
            "created_at": "={{ $json.created_at }}",
            "client_name": "={{ $json.client_name }}",
            "next_steps_md": "={{ $json.next_steps_md }}",
            "maturity_stage": "={{ $json.maturity_stage }}",
            "kpi_highlights_md": "={{ $json.kpi_highlights_md }}",
            "financial_table_md": "={{ $json.financial_table_md }}",
            "executive_summary_text": "={{$json.executive_summary_text }}"
          },
          "schema": [
            {
              "id": "row_key",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "row_key",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "audit_id",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "audit_id",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "client_name",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "client_name",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "sector",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "sector",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "maturity_stage",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "maturity_stage",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "executive_summary_text",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "executive_summary_text",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "financial_table_md",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "financial_table_md",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "kpi_highlights_md",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "kpi_highlights_md",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "risks_md",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "risks_md",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "next_steps_md",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "next_steps_md",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "created_at",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "created_at",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            }
          ],
          "mappingMode": "defineBelow",
          "matchingColumns": [
            "row_key"
          ],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        },
        "options": {},
        "operation": "YOUR_BASE_ID",
        "sheetName": {
          "__rl": true,
          "mode": "name",
          "value": "Executive_Summary.csv"
        },
        "documentId": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $('Set Client Config').first().json.master_sheet_id }}"
        }
      },
      "executeOnce": false,
      "typeVersion": 4.5
    },
    {
      "id": "40617211-8f27-41af-8d51-08e1e343ca03",
      "name": "Write KPI Benchmarking to Sheet",
      "type": "n8n-nodes-base.googleSheets",
      "position": [
        5040,
        3460
      ],
      "parameters": {
        "columns": {
          "value": {
            "unit": "unit",
            "metric": "metric",
            "status": "=status",
            "row_key": "={{ $json.row_key }}",
            "direction": "direction ",
            "client_value": "client_value",
            "industry_avg": "industry_avg",
            "best_in_class": "best_in_class",
            "gap_vs_avg_pct": "=gap_vs_avg_pct",
            "opportunity_value": "=opportunity_value"
          },
          "schema": [
            {
              "id": "row_key",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "row_key",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "metric",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "metric",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "client_value",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "client_value",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "industry_avg",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "industry_avg",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "best_in_class",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "best_in_class",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "direction",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "direction",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "unit",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "unit",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "gap_vs_avg_pct",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "gap_vs_avg_pct",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "status",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "status",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "opportunity_value",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "opportunity_value",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            }
          ],
          "mappingMode": "defineBelow",
          "matchingColumns": [
            "row_key"
          ],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        },
        "options": {},
        "operation": "YOUR_BASE_ID",
        "sheetName": {
          "__rl": true,
          "mode": "name",
          "value": "KPI_Benchmarking.csv"
        },
        "documentId": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $('Set Client Config').first().json.master_sheet_id }}"
        }
      },
      "executeOnce": false,
      "typeVersion": 4.5
    },
    {
      "id": "6461adac-d529-4079-9368-1c36f8bd5afd",
      "name": "Write KPI Snapshot to Sheet",
      "type": "n8n-nodes-base.googleSheets",
      "disabled": true,
      "position": [
        5350,
        3460
      ],
      "parameters": {
        "columns": {
          "value": {
            "metric": "={{ $json.metric }}",
            "row_key": "={{ $json.row_key }}",
            "client_value": "={{ $json.client_value }}",
            "industry_avg": "={{ $json.industry_average }}"
          },
          "schema": [
            {
              "id": "row_key",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "row_key",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "metric",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "metric",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "client_value",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "client_value",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "industry_avg",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "industry_avg",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "best_in_class",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "best_in_class",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "direction",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "direction",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "unit",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "unit",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "gap_vs_avg_pct",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "gap_vs_avg_pct",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "status",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "status",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "opportunity_value",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "opportunity_value",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            }
          ],
          "mappingMode": "defineBelow",
          "matchingColumns": [
            "row_key"
          ],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        },
        "options": {},
        "operation": "YOUR_BASE_ID",
        "sheetName": {
          "__rl": true,
          "mode": "name",
          "value": "KPI_Benchmarking.csv"
        },
        "documentId": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $('Set Client Config').first().json.master_sheet_id }}"
        }
      },
      "executeOnce": false,
      "typeVersion": 4.5
    },
    {
      "id": "85d3eae0-a06d-4874-9fb4-9d9a3fc40155",
      "name": "Split AI Projections Rows",
      "type": "n8n-nodes-base.splitOut",
      "position": [
        3490,
        3460
      ],
      "parameters": {
        "include": "selectedOtherFields",
        "options": {},
        "fieldToSplitOut": "client_models_rows",
        "fieldsToInclude": "audit_master_rows[0].audit_id"
      },
      "typeVersion": 1
    },
    {
      "id": "2afd9ec1-603c-489b-8d1b-f330e9adae20",
      "name": "AI Projections",
      "type": "n8n-nodes-base.googleSheets",
      "position": [
        1920,
        3210
      ],
      "parameters": {
        "columns": {
          "value": {
            "irr": "={{ $json.irr }}",
            "npv": "={{ $json.npv }}",
            "Owner": "={{ $json.owner }}",
            "row_key": "={{ $json.row_key }}",
            "Category": "={{ $json.catagory }}",
            "KPI Name": "={{ $json.kpi_name }}",
            "audit_id": "={{ $json.audit_id }}",
            "scenario": "={{ $json.scenario }}",
            "fte_saved": "={{ $json.fte_saved }}",
            "client_name": "={{ $json.client_name }}",
            "Target Value": "={{ $json.target_value }}",
            "Current Value": "={{ $json.current_value }}",
            "Improvement %": "={{ $json.improvement }}",
            "five_year_roi": "={{ $json.five_year_roi }}",
            "run_timestamp": "={{ $json.run_timestamp }}",
            "annual_benefit": "={{ $json.annual_benefit }}",
            "payback_months": "={{ $json.payback_months }}",
            "total_investment": "={{ $json.total_investment }}"
          },
          "schema": [
            {
              "id": "row_key",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "row_key",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "client_name",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "client_name",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "scenario",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "scenario",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "KPI Name",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "KPI Name",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "irr",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "irr",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "five_year_roi",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "five_year_roi",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "fte_saved",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "fte_saved",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "payback_months",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "payback_months",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "annual_benefit",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "annual_benefit",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "npv",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "npv",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "total_investment",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "total_investment",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "audit_id",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "audit_id",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "run_timestamp",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "run_timestamp",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Current Value",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "Current Value",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Target Value",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "Target Value",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Improvement %",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "Improvement %",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Category",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "Category",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Owner",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "Owner",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Updated By",
              "type": "string",
              "display": true,
              "removed": true,
              "required": false,
              "displayName": "Updated By",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Updated Date",
              "type": "string",
              "display": true,
              "removed": true,
              "required": false,
              "displayName": "Updated Date",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            }
          ],
          "mappingMode": "defineBelow",
          "matchingColumns": [
            "row_key"
          ],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        },
        "options": {},
        "operation": "YOUR_BASE_ID",
        "sheetName": {
          "__rl": true,
          "mode": "name",
          "value": "AI_Projections"
        },
        "documentId": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $('Set Client Config').first().json.master_sheet_id }}"
        }
      },
      "typeVersion": 4.7
    },
    {
      "id": "b7fcf2c4-6ac2-4b91-a2c7-5b9d6bd33359",
      "name": "Set Client Config",
      "type": "n8n-nodes-base.set",
      "position": [
        1300,
        760
      ],
      "parameters": {
        "options": {},
        "assignments": {
          "assignments": [
            {
              "id": "90facc02-a272-4e9d-9088-31e0cd518a82",
              "name": "client_name",
              "type": "string",
              "value": "Example Organisation"
            },
            {
              "id": "0412d133-8c05-4142-b017-da31384cf7cd",
              "name": "sector",
              "type": "string",
              "value": "Marketing & Creative Production"
            },
            {
              "id": "3720e27f-cd30-4945-90e1-991de6779414",
              "name": "maturity_stage",
              "type": "string",
              "value": "Walk"
            },
            {
              "id": "2ec48420-b84f-449b-aef3-553b727e78a5",
              "name": "market_count",
              "type": "number",
              "value": 5
            },
            {
              "id": "94d5f838-08c6-47ca-8ee5-830bb75a64dc",
              "name": "notification_email",
              "type": "string",
              "value": "YOUR_NOTIFICATION_EMAIL"
            },
            {
              "id": "YOUR_GOOGLE_RESOURCE_ID",
              "name": "org_drive_file_id",
              "type": "string",
              "value": "YOUR_ORG_DOCUMENT_FILE_ID"
            },
            {
              "id": "d77018f2-5413-468c-a397-4947b2d46078",
              "name": "master_sheet_id",
              "type": "string",
              "value": "YOUR_MASTER_GOOGLE_SHEET_ID"
            },
            {
              "id": "8b1b9fc5-bc82-4ed8-a0de-918902acfc44",
              "name": "output_drive_folder_id",
              "type": "string",
              "value": "YOUR_OUTPUT_DRIVE_FOLDER_ID"
            },
            {
              "id": "bf2208a8-9857-40e7-b829-fe6736420b4e",
              "name": "slack_channel_id",
              "type": "string",
              "value": "YOUR_SLACK_CHANNEL_ID"
            },
            {
              "id": "07841097-a70e-45b6-a6bc-fff83495f1a0",
              "name": "avg_fte_cost",
              "type": "number",
              "value": 85000
            },
            {
              "id": "3b4d027e-4395-4fc6-82f0-55cf302a9a1c",
              "name": "hours_per_fte_year",
              "type": "number",
              "value": 1800
            },
            {
              "id": "369b8eca-a114-4b89-9346-4cba3a6eec40",
              "name": "software_license_annual",
              "type": "number",
              "value": 25000
            },
            {
              "id": "65532c9d-5c4a-4b21-ba1c-51f7ee6e294b",
              "name": "integration_cost_per_system",
              "type": "number",
              "value": 15000
            },
            {
              "id": "2a47ccb5-d215-4910-9f67-d4d2b310d01c",
              "name": "training_cost_per_fte",
              "type": "number",
              "value": 2500
            },
            {
              "id": "f1e4a17d-8849-400a-8cfe-2cb8fecabde8",
              "name": "change_management_pct",
              "type": "number",
              "value": 0.15
            },
            {
              "id": "41d5aa6f-e0c9-4523-9a19-632a4d9bd7a3",
              "name": "discount_rate",
              "type": "number",
              "value": 0.1
            },
            {
              "id": "38c32626-4e0a-4200-976a-225d98d5b9cc",
              "name": "implementation_risk_buffer",
              "type": "number",
              "value": 0.2
            },
            {
              "id": "9bca4bb9-260d-402c-87a0-2a308f256988",
              "name": "benefit_realization_factor",
              "type": "number",
              "value": 0.85
            },
            {
              "id": "221299ab-9c91-484d-a40e-6c44efccd725",
              "name": "analysis_years",
              "type": "number",
              "value": 5
            },
            {
              "id": "cc56dc50-46cb-44e6-b613-66b5061a2afd",
              "name": "adkar_awareness",
              "type": "number",
              "value": 5
            },
            {
              "id": "39654243-9927-42c5-9d22-949b02c95c5b",
              "name": "adkar_desire",
              "type": "number",
              "value": 5
            },
            {
              "id": "80339c07-5fb9-4b40-b2e5-0bb9a0fb8d4c",
              "name": "adkar_knowledge",
              "type": "number",
              "value": 5
            },
            {
              "id": "eea30a26-7146-4e9b-b5c5-0f7e1b8b0e3a",
              "name": "adkar_ability",
              "type": "number",
              "value": 5
            },
            {
              "id": "ee2ba7ad-d57d-4329-9443-e7c32dafcac3",
              "name": "adkar_reinforcement",
              "type": "number",
              "value": 5
            },
            {
              "id": "3c8e7daf-YOUR_GOOGLE_RESOURCE_ID",
              "name": "stakeholders_json",
              "type": "string",
              "value": "[{\"name\": \"Executive Sponsor\", \"power\": \"High\", \"interest\": \"High\", \"current_stance\": \"Supportive\"}, {\"name\": \"Operations Lead\", \"power\": \"Medium\", \"interest\": \"High\", \"current_stance\": \"Neutral\"}, {\"name\": \"Technology Lead\", \"power\": \"High\", \"interest\": \"High\", \"current_stance\": \"Supportive\"}, {\"name\": \"People / Change Lead\", \"power\": \"Medium\", \"interest\": \"Medium\", \"current_stance\": \"Neutral\"}]"
            },
            {
              "id": "dd6b831d-6440-4701-9436-f293263f8cdf",
              "name": "audit_id",
              "type": "string",
              "value": "={{ 'AUDIT_' + $now.toFormat('yyyyLLdd_HHmmss') }}"
            },
            {
              "id": "d80c0990-4b61-487c-98c9-1a33b97726f7",
              "name": "audit_timestamp",
              "type": "string",
              "value": "={{ $now.toISO() }}"
            },
            {
              "id": "f9ea4f71-f004-4c14-929f-be7b04dca046",
              "name": "trigger_source",
              "type": "string",
              "value": "manual_config"
            }
          ]
        }
      },
      "typeVersion": 3.4
    }
  ],
  "active": false,
  "settings": {
    "binaryMode": "separate",
    "availableInMCP": false,
    "executionOrder": "v1"
  },
  "versionId": "651045f4-895f-4cbf-8369-7f8dd8217d7c",
  "nodeGroups": [],
  "connections": {
    "Upload file": {
      "main": [
        [
          {
            "node": "Limit to First Item (Notifications)",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Final Payload": {
      "main": [
        [
          {
            "node": "Limit to First Item (Notifications)1",
            "type": "main",
            "index": 0
          },
          {
            "node": "Split Client Models Rows",
            "type": "main",
            "index": 0
          },
          {
            "node": "Split Rationale Rows",
            "type": "main",
            "index": 0
          },
          {
            "node": "Split Diagrams Rows",
            "type": "main",
            "index": 0
          },
          {
            "node": "Split Recommendations Rows",
            "type": "main",
            "index": 0
          },
          {
            "node": "Split RACI Rows",
            "type": "main",
            "index": 0
          },
          {
            "node": "Split AI Projections Rows",
            "type": "main",
            "index": 0
          },
          {
            "node": "Split Audit Master Rows",
            "type": "main",
            "index": 0
          },
          {
            "node": "Split Exec Summary Rows",
            "type": "main",
            "index": 0
          },
          {
            "node": "Split KPI Benchmarking Rows",
            "type": "main",
            "index": 0
          },
          {
            "node": "Split KPI Snapshot Rows",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Split RACI Rows": {
      "main": [
        [
          {
            "node": "Write New RACI to Sheet",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "2.1 Data Cleaner": {
      "main": [
        [
          {
            "node": "2.2 Analyse Inefficiencies With OpenAI",
            "type": "main",
            "index": 0
          },
          {
            "node": "2.3 Map AI and Automation Opportunities",
            "type": "main",
            "index": 0
          },
          {
            "node": "2.4a Google Sheets - Benchmarks",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Set Client Config": {
      "main": [
        [
          {
            "node": "Industry Template Selector",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Split Diagrams Rows": {
      "main": [
        [
          {
            "node": "Write Diagrams to Sheet",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Merge Discovery Data": {
      "main": [
        [
          {
            "node": "2.1 Data Cleaner",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Split Rationale Rows": {
      "main": [
        [
          {
            "node": "Write Rationale to Sheet",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Merge Analysis Results": {
      "main": [
        [
          {
            "node": "Limit to First Item (Before Executive Summary)",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Split Audit Master Rows": {
      "main": [
        [
          {
            "node": "Write Audit Master to Sheet",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Split Exec Summary Rows": {
      "main": [
        [
          {
            "node": "Write Exec Summary to Sheet",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Split KPI Snapshot Rows": {
      "main": [
        [
          {
            "node": "Write KPI Snapshot to Sheet",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Split Client Models Rows": {
      "main": [
        [
          {
            "node": "4.1 Write Operating Model to Google Sheets",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "2.4b Benchmark Comparator": {
      "main": [
        [
          {
            "node": "Merge Analysis Results",
            "type": "main",
            "index": 1
          }
        ]
      ]
    },
    "Split AI Projections Rows": {
      "main": [
        [
          {
            "node": "AI Projections",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Industry Template Selector": {
      "main": [
        [
          {
            "node": "1.1 Google Drive - Org Data",
            "type": "main",
            "index": 0
          },
          {
            "node": "1.2 Google Sheets - RACI Matrix",
            "type": "main",
            "index": 0
          },
          {
            "node": "1.3 Google Sheets - Tools Inventory",
            "type": "main",
            "index": 0
          },
          {
            "node": "1.4 KPI Snapshot - Google Sheets",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Split Recommendations Rows": {
      "main": [
        [
          {
            "node": "4.1b Write Recommendations to Google Sheets",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "1.1 Google Drive - Org Data": {
      "main": [
        [
          {
            "node": "Merge Discovery Data",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Split KPI Benchmarking Rows": {
      "main": [
        [
          {
            "node": "Write KPI Benchmarking to Sheet",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Generate Professional Report": {
      "main": [
        [
          {
            "node": "Upload file",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Manual Trigger - Start Audit": {
      "main": [
        [
          {
            "node": "Set Client Config",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "3.2 Financial Model Deep-Dive": {
      "main": [
        [
          {
            "node": "Extract KPI Updates",
            "type": "main",
            "index": 0
          },
          {
            "node": "3.3b Change Management Framework",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Optional - Send Email Summary": {
      "main": [
        [
          {
            "node": "Optional - Mark Queue Complete",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Optional - Watch Client Queue": {
      "main": [
        [
          {
            "node": "Optional - Map Queue Row to Config",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Limit to First Item (Supabase)": {
      "main": [
        [
          {
            "node": "Optional - Store Assessment in Supabase",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "1.2 Google Sheets - RACI Matrix": {
      "main": [
        [
          {
            "node": "Merge Discovery Data",
            "type": "main",
            "index": 1
          }
        ]
      ]
    },
    "2.4a Google Sheets - Benchmarks": {
      "main": [
        [
          {
            "node": "2.4b Benchmark Comparator",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Limit to First Item (Rationale)": {
      "main": [
        [
          {
            "node": "3.5 Consultant Rationale Generator",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "1.4 KPI Snapshot - Google Sheets": {
      "main": [
        [
          {
            "node": "2.1 Data Cleaner",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Optional - Map Queue Row to Config": {
      "main": [
        [
          {
            "node": "Optional - Mark Queue Processing",
            "type": "main",
            "index": 0
          },
          {
            "node": "Industry Template Selector",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "1.3 Google Sheets - Tools Inventory": {
      "main": [
        [
          {
            "node": "2.1 Data Cleaner",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "3.1 Generate Target Operating Model": {
      "main": [
        [
          {
            "node": "3.2 Financial Model Deep-Dive",
            "type": "main",
            "index": 0
          },
          {
            "node": "3.3 Visual Schema Builder",
            "type": "main",
            "index": 0
          },
          {
            "node": "Extract New RACI",
            "type": "main",
            "index": 0
          },
          {
            "node": "3.3a Mermaid Diagram Generator",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Limit to First Item (Notifications)": {
      "main": [
        [
          {
            "node": "Final Payload",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Limit to First Item (Notifications)1": {
      "main": [
        [
          {
            "node": "Optional - Send Email Summary",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "3.4A Prepare Executive Report Context": {
      "main": [
        [
          {
            "node": "3.4 Generate Executive Transformation Report",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "2.2 Analyse Inefficiencies With OpenAI": {
      "main": [
        [
          {
            "node": "Merge Analysis Results",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "2.3 Map AI and Automation Opportunities": {
      "main": [
        [
          {
            "node": "Merge Analysis Results",
            "type": "main",
            "index": 1
          }
        ]
      ]
    },
    "Optional - Store Assessment in Supabase": {
      "main": [
        [
          {
            "node": "Optional - Extract Reusable Patterns",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "3.4 Generate Executive Transformation Report": {
      "main": [
        [
          {
            "node": "Extract Recommendations Data",
            "type": "main",
            "index": 0
          },
          {
            "node": "Generate Professional Report",
            "type": "main",
            "index": 0
          },
          {
            "node": "Limit to First Item (Rationale)",
            "type": "main",
            "index": 0
          },
          {
            "node": "Parse",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Limit to First Item (Before Executive Summary)": {
      "main": [
        [
          {
            "node": "3.1 Generate Target Operating Model",
            "type": "main",
            "index": 0
          },
          {
            "node": "3.4A Prepare Executive Report Context",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  }
}