HomeAI AutomationHow to Build an AI Invoice…
AI Automation

How to Build an AI Invoice Analyzer & Cash Flow Predictor with n8n, Gemini, Google Sheets & Slack

How to Build an AI Invoice Analyzer & Cash Flow Predictor with n8n, Gemini, Google Sheets & Slack

Every finance team faces the same slow, error-prone cycle: invoices arrive by email, someone manually logs them in a spreadsheet, another person checks if the vendor looks legitimate, and a third person tries to figure out how this payment affects the month-end cash position. This tutorial shows you how to collapse all four of those steps into a single n8n workflow powered by Google Gemini AI — one that analyzes invoices for fraud, logs them automatically, predicts cash flow impact, and emails a report to your team.

By the end you’ll have a live automation that accepts invoice submissions through a form, uses Gemini Flash to flag anomalies and classify spend categories, alerts your Slack channel when a high-risk invoice appears, appends every invoice to a Google Sheets financial database, runs a 30-day cash flow prediction, and delivers a formatted HTML report via Gmail. Total setup time: about 30 minutes.

💡 Who this is for: Freelancers, small businesses, and ops teams processing more than 10–15 invoices per month who want AI-assisted review without paying for expensive AP automation software.

Want to skip the build and get the ready-to-import template? Download the workflow + setup guides here.

What the Workflow Does

Here’s the full automation at a glance:

  1. Invoice Upload Form — An n8n form page your team can bookmark. Vendors or staff submit invoice details (vendor, amount, dates, description).
  2. Format Invoice Data — A Code node that normalizes the input, calculates days-until-due, and timestamps the submission.
  3. AI Invoice Analyzer (Gemini) — Sends the invoice to Gemini Flash with a structured prompt. Returns fraud risk level, spend category, payment priority, and a one-line summary — all as JSON.
  4. Parse AI Response — Extracts the JSON from Gemini’s output with a safe fallback in case of model formatting errors.
  5. Fraud Risk Check (IF node) — Routes the flow: high-risk invoices go to Slack and Google Sheets; normal invoices go directly to Sheets.
  6. Send Fraud Alert to Slack — Posts a formatted block message to #fraud-alerts with vendor, amount, and a list of the specific risk reasons Gemini identified.
  7. Log to Financial Database — Appends a row to your Google Sheets invoice tracker (12 columns: date, vendor, amount, category, fraud risk, etc.).
  8. Cash Flow Predictor (Gemini) — A second Gemini chain that takes the logged invoice data and returns a cash flow assessment: impact direction, urgency score 1–10, recommended payment date, and three action items.
  9. Email Cash Flow Report — Sends a formatted HTML email via Gmail with the full analysis — everything from fraud risk to recommended payment date.

Prerequisites

Before you import the workflow, make sure you have the following:

  • n8n — self-hosted (v1.0+) or n8n Cloud. The workflow uses nodes available in both.
  • Google Gemini API key — Free tier works for low volumes. Get yours at aistudio.google.com.
  • Google Sheets — Create a spreadsheet called “Invoice Tracker” with a sheet tab named “Invoices”. Leave the first row for headers (the workflow will create them on first run).
  • Slack workspace — Create a #fraud-alerts channel (or rename to match an existing one).
  • Gmail account — Any Gmail or Google Workspace account for sending reports.

Step-by-Step Setup

1Import the Workflow into n8n

Download the .json file from the template package. In n8n, click + New Workflow → Import from File. Select the JSON and click Import. The canvas will load with all 16 nodes connected and labeled.

Note: The workflow imports in inactive state. Do not activate it until you’ve connected all credentials and updated the two placeholder values below.

2Connect Your Credentials

Open each node that has a credential warning (indicated by a red dot) and connect the appropriate account:

Node Credential Type Where to Get It
Gemini Flash – Invoice Analysis Google Gemini (PaLM) API Google AI Studio → API Keys
Gemini Flash – Cash Flow Google Gemini (PaLM) API Same key as above
Log to Financial Database Google Sheets OAuth2 n8n Credentials → Google Sheets OAuth2
Send Fraud Alert to Slack Slack OAuth2 Slack App → OAuth tokens
Email Cash Flow Report Gmail OAuth2 n8n Credentials → Gmail OAuth2

The Credentials Guide PDF (included in the download) walks through each one with exact screenshots and scopes required.

3Update the Two Placeholders

Open the Log to Financial Database node. In the Document ID field, replace YOUR_SPREADSHEET_ID with your Google Sheets spreadsheet ID — the long alphanumeric string in the sheet’s URL between /d/ and /edit.

Open the Email Cash Flow Report node. In the To field, replace YOUR_FINANCE_EMAIL@company.com with the email address that should receive cash flow reports.

4Set Up Your Google Sheet Structure

The workflow will auto-append rows, but it expects the “Invoices” sheet to exist. Open your spreadsheet, rename Sheet1 to Invoices, and optionally add these headers in row 1 (the workflow will use them for column matching):

Submitted At | Vendor | Invoice Number | Invoice Date | Due Date | Amount | Currency | Category | Fraud Risk | Fraud Reasons | Payment Priority | Summary

5Configure the Slack Alert Channel

Open the Send Fraud Alert to Slack node. The default channel is #fraud-alerts. Change this to match your Slack channel name. Make sure the Slack app you connected has the chat:write permission scope.

6Test with a Sample Invoice

Before activating, run a manual test. Click the Invoice Upload Form node, then click Test StepOpen Test URL. A form page opens in your browser. Submit a test invoice:

  • Vendor: Test Vendor Ltd
  • Invoice #: INV-2024-001
  • Amount: 9999 (high amount triggers fraud check)
  • Due Date: tomorrow’s date (short due date = fraud indicator)
  • Description: leave blank (missing description = another indicator)

This combination should produce a high fraud risk result, triggering the Slack alert path. Watch the n8n canvas — green checkmarks confirm each node ran successfully.

7Activate and Share the Form URL

Once your test passes, toggle the workflow to Active. Go back to the Invoice Upload Form node and copy the production form URL. Share this with your team or embed it in your internal tools documentation. Anyone with the link can submit invoices — no n8n account needed.

Understanding the Gemini Prompts

The workflow uses two separate Gemini chains, each with a specific job. Understanding them helps you customize the AI behavior.

Invoice Analysis Prompt

The first chain asks Gemini to evaluate fraud risk based on five signals: unusually round amounts, very short due dates (under 3 days), missing service descriptions, high total amounts, and suspicious vendor name patterns. It returns a structured JSON object with fraudRisk (low/medium/high), fraudReasons (an array of specific red flags), category (spend type), and paymentPriority.

You can tune the sensitivity by editing the prompt in the AI Invoice Analyzer node. For example, adding your company’s typical invoice range (e.g., “invoices over $50,000 require extra scrutiny”) will make the fraud detection more context-aware.

Cash Flow Prediction Prompt

The second chain receives the analyzed invoice plus the days-until-due count and asks Gemini to assess impact on your 30-day cash position. It returns cashFlowImpact (positive/negative/neutral), an urgencyScore from 1–10, a recommendedPaymentDate, and three concrete actionItems.

The model used in both chains is Gemini 1.5 Flash — fast and affordable. For larger invoices or more complex categorization, you can switch the model name to models/gemini-1.5-pro in both Gemini nodes with no other changes required.

Customization Ideas

  • Add a budget limit check — Insert an IF node after the Sheets log to check if amount > 10000 and route those to a separate “large purchase approval” Slack channel.
  • Multi-approver flow — For high-priority invoices, add a Wait node + webhook to pause the workflow until a manager clicks an approval link in Slack or email before the report is sent.
  • Recurring invoice detection — Add a Google Sheets read step to compare the vendor name against your existing database. Flag invoices from known vendors that arrive outside their normal billing cycle.
  • Currency conversion — Insert an HTTP Request node before the Sheets log to call a live exchange rate API (e.g., Frankfurter) and normalize all amounts to your base currency.
  • Airtable instead of Google Sheets — Replace the Google Sheets node with an Airtable “Create Record” action. The data structure maps 1:1.

Troubleshooting

Gemini returns text instead of JSON — The prompt explicitly says “no markdown, no code fences.” If Gemini occasionally wraps the JSON in triple backticks, the Parse AI Response Code node handles this with a regex fallback. No action needed.

Google Sheets “Resource not found” error — Double-check the spreadsheet ID in the Log to Financial Database node. The ID is the long string in your sheet URL: https://docs.google.com/spreadsheets/d/THIS_PART/edit.

Slack “channel_not_found” error — Make sure the Slack app is installed in the workspace and the channel name in the node matches exactly (including the # or without it — n8n accepts both).

Form not accessible after activation — The form URL only works when the workflow is active. Check the toggle in the top-right of the workflow editor.

The Complete Node Structure

Node Type Purpose
Invoice Upload Form Form Trigger Accept submissions from team/vendors
Format Invoice Data Code Normalize fields, calculate days-until-due
AI Invoice Analyzer LLM Chain Gemini fraud analysis + categorization
Gemini Flash – Invoice Analysis Google Gemini Chat Model AI sub-node for Invoice Analyzer chain
Parse AI Response Code Extract JSON from AI output (with fallback)
Fraud Risk Check IF Route high-risk vs normal invoices
Send Fraud Alert to Slack Slack Block message to #fraud-alerts channel
Log to Financial Database Google Sheets Append row to Invoices tracker
Cash Flow Predictor LLM Chain Gemini 30-day cash flow analysis
Gemini Flash – Cash Flow Google Gemini Chat Model AI sub-node for Cash Flow Predictor chain
Email Cash Flow Report Gmail Send formatted HTML report

Get the Ready-to-Use Template

Includes the workflow JSON, a step-by-step Setup Guide PDF, and a Credentials Guide PDF with screenshots for every API connection.

Download — $14.99