ChatGPTSalesFinding leadsAI score · 73/100AI-assisted edit · no obvious prompt-injection riskn8n.io

n8n Automated Business KPI Insights: GPT-4-Powered MSSQL & Multi-Channel Daily Reports

Daily auto-aggregate MSSQL, Google Analytics, Sheets data → calculate ROAS/CAC → AI-generated summary → WhatsApp/email push

ExperiencedStepsWorkflowPromptTip
Who
Founders, ops leads, or small teams who need daily visibility on revenue, CAC, and marketing efficiency
You get
Receive concise daily notifications with key metrics, risk alerts, and action recommendations without manual dashboards
You need
n8n · google-sheets · email · whatsapp

Constraints

Prerequisites: an n8n instance (self-hosted or cloud); credentials required: microsoftSql, googleAnalyticsOAuth2, googleApi (service account), smtp, openAiApi, whatsAppApi. SQL queries and document IDs in the source are placeholders and must be replaced with real business data.

What they did

Template author mohamed-abubakkar built an AI-powered business intelligence agent on n8n. The workflow triggers daily via Schedule Trigger, collects yesterday's revenue, new registered users, total visitors, and marketing spend in parallel from MSSQL, Google Analytics, and Google Sheets; validates data completeness via IF nodes; normalizes and merges into a unified JSON through Summarize and Code nodes; calculates ROAS and CAC, then applies rule-based risk scoring; finally generates a concise business summary, risk, opportunity, and action via an AI Agent (OpenAI gpt-4.1-mini) and pushes the result through WhatsApp and email.

How it went

The source displays complete node configurations, connections, and example input/output JSON (e.g., revenue=4290 yields ROAS=5.36, CAC=40, agentStatus=normal). The author states the workflow runs fully automated daily without manual dashboards. However, no real-world execution logs, long-term stability data, or ROI validation are provided (author_report).

Worth knowing

1. SQL queries (SELECT * from yourtable) and Google Sheets documentId in the source are placeholders and must be replaced with your actual business data. 2. The Google Analytics propertyId caches the author's value—replace with your own GA4 property ID. 3. Growth fields (revenueGrowthPct, userGrowthPct) are commented out in KPI Calculator; uncomment and ensure yesterday data fields are passed if MoM/WoW comparison is needed. 4. AI Agent systemMessage and user prompt can be customized per business context; the model can be swapped to gpt-4.1 or gpt-4. 5. Slack/Telegram are mentioned in sticky notes but not included in workflow.json—add manually if needed. 6. Error handling only sends email alerts; no auto-retry or fallback strategy is provided. 7. This site has not imported or executed the workflow; validate each Code node's input/output with test data after setup.

n8n workflow template

Structure checked · Not run-tested

Use “Import from File” in n8n, or copy the JSON and paste it into the editor. Connect your own accounts, then try test data. The template is inactive by default.

Setup and test checklist

Credentials to connect

  • Yesterday's Revenue node: connect microsoftSql credentials.
  • Yesterday's Registered Users node: connect microsoftSql credentials.
  • Yesterday's Report node: connect googleAnalyticsOAuth2 credentials.
  • Yesterday's Marketing Expenses node: connect googleApi credentials.
  • Send Error Email node: connect smtp credentials.
  • OpenAI Chat Model node: connect OpenAI API credentials.
  • Send message node: connect whatsAppApi credentials.
  • Send Final Email node: connect smtp credentials.

Configuration to replace

  • Source template is n8n public workflow #12008 (~31 nodes). Keep inactive after import; verify triggers, expressions and external API endpoints.
  • Sticky-note guidance is informational; replace placeholders with your own accounts, sheet schemas or channel IDs.

Test input and expected output

  • Manually run the main path once in a test workspace and confirm credentialed nodes authenticate without errors.
  • Drive one synthetic/redacted sample through and check output fields and downstream writes before enabling in production.

Template changes

  • Author credential bindings, webhookId and execution data are removed; the workflow is inactive. Nodes, connections and original prompts are preserved. Not run-tested in n8n.
  • No business-logic edits; verify keys, quotas and privacy compliance before use.

Template retrieved: 2026-10-24

Steps

  1. Configure data source nodes

    Set up four parallel data collection nodes in n8n: 1) Yesterday's Revenue (Microsoft SQL node) connects to your MSSQL database—replace the default query SELECT * from yourtable with your actual table and fields for yesterday's revenue; 2) Yesterday's Registered Users (Microsoft SQL node) similarly replace the query for new sign-ups; 3) Yesterday's Report (Google Analytics node) set propertyId to your own GA4 property ID with dateRange: yesterday; 4) Yesterday's Marketing Expenses (Google Sheets node) authenticate via service account and replace documentId and sheetName with your actual spend sheet. All nodes require pre-configured credentials in n8n's credential manager.

  2. Add data validation and error alerts

    Add IF nodes after each data source (Check data, If, Condition for google report, Condition for marketing reports) to verify upstream data exists (using exists condition). If any source is missing, route to the Send Error Email node with the pre-filled error message. Replace toEmail/fromEmail with your actual operations email.

    Execution prompt · Source text。Send Error Email node text field

    Dear User,
    
    Daily business intelligence workflow failed due to missing input data.
    One or more required sources did not return valid results.
    Action: Review individual data source logs and resolve before next run.
  3. Normalize and merge data

    Use Summarize/Set nodes to extract key fields: Get only Total Revenue Amount (sum TotalAmount), Get only Total Users (count email), Get Only Total Users (extract totalUsers), Get only Total Spend Amount (sum Ad Spend). Then merge all four branches with Merge all result, followed by Normalize the data (Code node) to unify into a single JSON object: {revenue, registeredUsers, totalUsers, adSpend}.

    Execution prompt · Source text。Normalize the data node jsCode field

    const result = {
      revenue: 0,
      registeredUsers: 0,
      totalUsers: 0,
      adSpend: 0
    };
    
    for (const item of items) {
      if (item.json.sum_TotalAmount !== undefined) {
        result.revenue = item.json.sum_TotalAmount;
      }
    
      if (item.json.count_email !== undefined) {
        result.registeredUsers = item.json.count_email;
      }
    
      if (item.json["Total Users"] !== undefined) {
        result.totalUsers = item.json["Total Users"];
      }
    
      if (item.json.sum_Ad_Spend !== undefined) {
        result.adSpend = item.json.sum_Ad_Spend;
      }
    }
    
    return [{ json: result }];
  4. Calculate KPIs and apply business rules

    Connect to KPI Calculator (Code node) to compute ROAS (revenue/adSpend) and CAC (adSpend/registeredUsers), rounded to 2 decimals. Then connect to Business Decision Logic (Code node) to tag status: ROAS < 1 → high risk (marketing not generating returns); ROAS ≥ 3 → strong performance; CAC > 100 → medium risk (high acquisition cost). Output includes agentStatus, agentPriority, and insights array.

    Execution prompt · Source text。KPI Calculator node jsCode field

    const revenue = Number($json.revenue) || 0;
    const adSpend = Number($json.adSpend) || 0;
    const users = Number($json.registeredUsers) || 0;
    
    // Optional: yesterday values (if available later)
    const yesterdayRevenue = Number($json.yesterdayRevenue) || 0;
    const yesterdayUsers = Number($json.yesterdayUsers) || 0;
    
    // KPI calculations
    const ROAS = adSpend > 0 ? revenue / adSpend : 0;
    const CAC = users > 0 ? adSpend / users : 0;
    
    // Growth calculations
    const revenueGrowthPct =
      yesterdayRevenue > 0
        ? ((revenue - yesterdayRevenue) / yesterdayRevenue) * 100
        : 0;
    
    const userGrowthPct =
      yesterdayUsers > 0
        ? ((users - yesterdayUsers) / yesterdayUsers) * 100
        : 0;
    
    return [
      {
        json: {
          ...$json,
          ROAS: Number(ROAS.toFixed(2)),
          CAC: Number(CAC.toFixed(2)),
          //revenueGrowthPct: Number(revenueGrowthPct.toFixed(2)),
          //userGrowthPct: Number(userGrowthPct.toFixed(2))
        }
      }
    ];

    Execution prompt · Source text。Business Decision Logic node jsCode field

    const kpi = $json;
    
    let status = "normal";
    let priority = "low";
    let insights = [];
    
    if(kpi.ROAS < 1){
      status = "risk";
      priority = "high";
      insights.push("Marketing spend is not generating returns");
    }
    
    if(kpi.ROAS >= 3){
      insights.push("Marketing campaigns are perfoming very well");
    }
    
    if(kpi.CAC > 100){
      status = "risk";
      priority = "medium";
      insights.push("Customer acquision cost is high");
    }
    
    return [{
      json: {
        ...kpi,
        agentStatus: status,
        agentPriority: priority,
        insights
      }
    }];
  5. Generate AI business summary

    Configure the AI Agent node with promptType: define. Connect the OpenAI Chat Model node (default gpt-4.1-mini, swappable to gpt-4.1 or gpt-4) as the language model, and Calculator as an optional tool. The AI Agent user prompt receives the upstream KPI JSON; the systemMessage sets the role as a founder's assistant, requiring output of: one-line summary, one risk (if any), one opportunity, one recommended action.

    Execution prompt · Source text。AI Agent node text field (user prompt)

    =Business KPIs:
    {{ JSON.stringify($json) }}
    
    Write:
    1. One-line business summary
    2. One risk (if any)
    3. One opportunity
    4. One recommended action

    Execution prompt · Source text。AI Agent node options.systemMessage field

    You are an AI business agent working for a company founder.
    
    Your job:
    - Analyze business KPIs
    - Explain what is happening
    - Decide if a notification is required
    - Keep the message short, clear, and actionable
    - Do not use technical terms
    - Do not exaggerate
  6. Format and push multi-channel notifications

    Feed AI Agent output into a Merge node combined with raw KPI data, then distribute simultaneously to: 1) Send message (WhatsApp node) with textBody containing the AI summary plus four metrics; 2) Send Final Email (Email node) with subject Yesterday's Revenue Report. Both body templates are pre-filled—replace recipient contacts. The source also mentions extensibility to Slack/Telegram (add nodes manually).

    Execution prompt · Source text。Send message (WhatsApp) node textBody field

    ={{ $json.output }}
    
    Revenue :- {{ $json.revenue }}
    New Users :- {{ $json.registeredUsers }}
    Total Users :- {{ $json.totalUsers }}
    Total Ad Spend :- {{ $json.adSpend }}

    Execution prompt · Source text。Send Final Email node text field

    =Dear User,
    
    {{ $json.output }}
    
    Revenue :- {{ $json.revenue }}
    New Users :- {{ $json.registeredUsers }}
    Total Users :- {{ $json.totalUsers }}
    Total Ad Spend :- {{ $json.adSpend }}

Prompt you can copy

Setup guidance · Editorial suggestion。Hand to setup assistant; confirm inputs and permissions first

This block is the prompt. Ads are never placed here.

You are setting up an n8n automated business KPI daily report workflow. Please confirm in this order: 1) n8n instance and six credentials ready (MSSQL, Google Analytics OAuth2, Google API service account, SMTP, OpenAI API, WhatsApp API); 2) all placeholder queries and document IDs replaced; 3) Schedule Trigger daily execution time set; 4) error notification email configured; 5) single-node data return tested. Recommend testing with sample data through the Normalize the data node before enabling the AI Agent.

Replace SQL and Sheets IDs first, test data flow node by node, then enable the schedule trigger.

Source

Automated business KPI insights with GPT-4, MSSQL, analytics & multi-channel alerts · mohamed-abubakkar · n8n.io · 2025-12-22

Comments & feedback

Tried this method? Share results, problems or improvements. Comments appear after moderation. Please avoid sensitive information.

Loading…

    Related