{
  "name": "Gmail invoices to Google Sheets with AI and GST/QST checks (FluxLogic SI)",
  "nodes": [
    {
      "id": "7c0a1e01-2026-4160-866c-00c0b9e191a0",
      "name": "Copyright",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -420,
        -560
      ],
      "parameters": {
        "content": "## Copyright\n\n© 2026 FluxLogic SI. Free to use in your business; may not be resold or redistributed as your own.",
        "height": 140,
        "width": 880,
        "color": 7
      }
    },
    {
      "id": "78d04569-be0c-5de6-908d-a512a7f2f736",
      "name": "What it does",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -420,
        -360
      ],
      "parameters": {
        "content": "## What it does\n1. Checks Gmail every hour for emails with a PDF that do not have the invoices-processed label.\n2. Reads the PDF text; the AI pulls supplier, date, amounts and GST/QST numbers.\n3. A fixed rule checks the sums and registration numbers.\n4. Saves one row in Google Sheets and labels the email.\n\nNothing is paid or sent: it only records. Check REVIEW rows by hand.",
        "height": 320,
        "width": 420,
        "color": 4
      }
    },
    {
      "id": "2cab535f-8865-58e9-a25c-e5a1f23aacdf",
      "name": "Before you turn it on",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        40,
        -360
      ],
      "parameters": {
        "content": "## Before you turn it on\n1. Connect your Gmail, Google Sheets and OpenAI accounts (credentials).\n2. Create the Gmail label invoices-processed and pick it in the last node.\n3. Create a sheet with a tab named Invoices and paste its URL in the Google Sheets node.\n4. Test with 3 or 4 real invoices and compare by hand.\n\nFull guide: fluxlogicsi.com",
        "height": 320,
        "width": 420,
        "color": 3
      }
    },
    {
      "id": "93da749f-553e-58be-af69-d71d744b9576",
      "name": "Gmail: emails with a PDF invoice",
      "type": "n8n-nodes-base.gmailTrigger",
      "typeVersion": 1.2,
      "position": [
        -420,
        100
      ],
      "parameters": {
        "simple": false,
        "filters": {
          "q": "has:attachment filename:pdf -label:invoices-processed"
        },
        "options": {
          "downloadAttachments": true
        },
        "pollTimes": {
          "item": [
            {
              "mode": "everyHour"
            }
          ]
        }
      }
    },
    {
      "id": "3b62c47f-e267-59e2-8386-d86cf83a77d7",
      "name": "Split PDFs",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        -200,
        100
      ],
      "parameters": {
        "jsCode": "// One item per PDF attachment. Non-PDF attachments are ignored.\nconst out = [];\nfor (const item of $input.all()) {\n  const bin = item.binary || {};\n  for (const key of Object.keys(bin)) {\n    const f = bin[key];\n    const isPdf = f.mimeType === 'application/pdf' || /\\.pdf$/i.test(f.fileName || '');\n    if (!isPdf) continue;\n    out.push({\n      json: {\n        email_id: item.json.id,\n        from: (item.json.from && (item.json.from.text || (item.json.from.value && item.json.from.value[0] && item.json.from.value[0].address))) || '',\n        subject: item.json.subject || '',\n        received: item.json.date || '',\n        file_name: f.fileName || key,\n      },\n      binary: { data: f },\n    });\n  }\n}\nreturn out;"
      }
    },
    {
      "id": "118249f1-fd64-5e89-a8fd-feebde843a72",
      "name": "Read PDF text",
      "type": "n8n-nodes-base.extractFromFile",
      "typeVersion": 1,
      "position": [
        20,
        100
      ],
      "parameters": {
        "operation": "pdf",
        "binaryPropertyName": "data",
        "options": {}
      }
    },
    {
      "id": "210d7161-87ef-5e90-96b3-49d25e3803de",
      "name": "Does the PDF have text?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2,
      "position": [
        240,
        100
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "loose"
          },
          "combinator": "and",
          "conditions": [
            {
              "id": "08378b76-dfe2-5567-be81-035f27b1d3af",
              "leftValue": "={{ ($json.text || '').trim().length }}",
              "rightValue": 40,
              "operator": {
                "type": "number",
                "operation": "gt"
              }
            }
          ]
        },
        "options": {}
      }
    },
    {
      "id": "cc54cfad-04f1-51e3-82c4-5a85c59ad0aa",
      "name": "AI: extract invoice data",
      "type": "@n8n/n8n-nodes-langchain.chainLlm",
      "typeVersion": 1.5,
      "position": [
        480,
        0
      ],
      "parameters": {
        "promptType": "define",
        "hasOutputParser": true,
        "text": "=You are an accounts payable assistant in Quebec. Read the invoice text between the <invoice> tags.\nExtract ONLY what is written. If a field is not there, leave it empty (null). Do not invent or calculate anything that is not on the invoice.\n- Amounts as numbers, no currency symbol (example: 1234.56).\n- tps = GST/HST charged. tvq = QST charged.\n- numero_tps_proveedor and numero_tvq_proveedor exactly as printed (example: 123456789 RT0001, 1234567890 TQ0001).\n- fecha_factura as YYYY-MM-DD.\n\n<invoice>\n{{ $json.text }}\n</invoice>"
      }
    },
    {
      "id": "3ce2c563-7469-5605-bd23-414129a17b5b",
      "name": "OpenAI model",
      "type": "@n8n/n8n-nodes-langchain.lmChatOpenAi",
      "typeVersion": 1.2,
      "position": [
        440,
        220
      ],
      "parameters": {
        "model": {
          "__rl": true,
          "mode": "list",
          "value": "gpt-4.1-mini",
          "cachedResultName": "gpt-4.1-mini"
        },
        "options": {
          "temperature": 0
        }
      }
    },
    {
      "id": "97c0815b-f261-52df-b6af-a2c586589871",
      "name": "Output format",
      "type": "@n8n/n8n-nodes-langchain.outputParserStructured",
      "typeVersion": 1.2,
      "position": [
        640,
        220
      ],
      "parameters": {
        "schemaType": "manual",
        "inputSchema": "{\n  \"type\": \"object\",\n  \"properties\": {\n    \"proveedor\": {\n      \"type\": [\n        \"string\",\n        \"null\"\n      ]\n    },\n    \"numero_factura\": {\n      \"type\": [\n        \"string\",\n        \"null\"\n      ]\n    },\n    \"fecha_factura\": {\n      \"type\": [\n        \"string\",\n        \"null\"\n      ]\n    },\n    \"facturado_a\": {\n      \"type\": [\n        \"string\",\n        \"null\"\n      ]\n    },\n    \"subtotal\": {\n      \"type\": [\n        \"number\",\n        \"null\"\n      ]\n    },\n    \"tps\": {\n      \"type\": [\n        \"number\",\n        \"null\"\n      ]\n    },\n    \"tvq\": {\n      \"type\": [\n        \"number\",\n        \"null\"\n      ]\n    },\n    \"total\": {\n      \"type\": [\n        \"number\",\n        \"null\"\n      ]\n    },\n    \"moneda\": {\n      \"type\": [\n        \"string\",\n        \"null\"\n      ]\n    },\n    \"numero_tps_proveedor\": {\n      \"type\": [\n        \"string\",\n        \"null\"\n      ]\n    },\n    \"numero_tvq_proveedor\": {\n      \"type\": [\n        \"string\",\n        \"null\"\n      ]\n    }\n  },\n  \"required\": [\n    \"proveedor\",\n    \"total\"\n  ]\n}"
      }
    },
    {
      "id": "9843a858-090c-5d45-849d-9981cf78d8c9",
      "name": "Check amounts and GST/QST numbers",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        860,
        0
      ],
      "parameters": {
        "mode": "runOnceForEachItem",
        "jsCode": "// Fixed rules, no AI: sums, tax rates and supplier registration numbers.\nconst d = $json.output || {};\nconst src = $('Split PDFs').item.json;\nconst n = (v) => (typeof v === 'number' && isFinite(v)) ? v : (v === null || v === undefined || v === '' ? null : (isFinite(Number(v)) ? Number(v) : null));\nconst sub = n(d.subtotal), tps = n(d.tps), tvq = n(d.tvq), tot = n(d.total);\nconst r = [];\nconst near = (a, b) => Math.abs(a - b) <= Math.max(0.05, Math.abs(b) * 0.01);\nif (tot === null) r.push(\"Total is missing\");\nif (sub !== null && tot !== null && !near(sub + (tps || 0) + (tvq || 0), tot)) r.push(\"Subtotal + GST + QST does not equal the total\");\nif (sub !== null && tps !== null && tps > 0 && !near(tps, sub * 0.05)) r.push(\"GST is not 5% of the subtotal (check for exempt items)\");\nif (sub !== null && tvq !== null && tvq > 0 && !near(tvq, sub * 0.09975)) r.push(\"QST is not 9.975% of the subtotal (check for exempt items)\");\nconst gst = String(d.numero_tps_proveedor || '').toUpperCase().replace(/[\\s-]/g, '');\nconst qst = String(d.numero_tvq_proveedor || '').toUpperCase().replace(/[\\s-]/g, '');\nif (tps > 0 && !/^\\d{9}RT\\d{4}$/.test(gst)) r.push(\"GST charged but no valid supplier GST number (9 digits + RT + 4)\");\nif (/^NR\\d{8}$/.test(qst)) r.push(\"NR-type QST number: that QST does not give an ITR\");\nelse if (tvq > 0 && !/^\\d{10}TQ\\d{4}$/.test(qst)) r.push(\"QST charged but no valid supplier QST number (10 digits + TQ + 4)\");\nif (!d.facturado_a) r.push(\"Cannot see who the invoice is billed to\");\nreturn { json: {\n  'received_date': src.received, 'sender': src.from, 'file': src.file_name,\n  'supplier': d.proveedor || '', 'invoice_number': d.numero_factura || '', 'invoice_date': d.fecha_factura || '',\n  'billed_to': d.facturado_a || '', 'subtotal': sub, 'gst': tps, 'qst': tvq, 'total': tot,\n  'currency': d.moneda || '', 'supplier_gst_number': d.numero_tps_proveedor || '', 'supplier_qst_number': d.numero_tvq_proveedor || '',\n  'status': r.length ? \"REVIEW\" : \"OK\", 'review_reasons': r.join(' | '),\n  'email_link': 'https://mail.google.com/mail/u/0/#all/' + src.email_id,\n} };"
      }
    },
    {
      "id": "7e7a1322-3cd0-5669-8a88-5f19d95dbd27",
      "name": "Scanned PDF: flag for review",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        860,
        400
      ],
      "parameters": {
        "mode": "runOnceForEachItem",
        "jsCode": "// No text to read: we do not send it to the AI (it would guess). Flag it for a person.\nconst src = $('Split PDFs').item.json;\nreturn { json: {\n  'received_date': src.received, 'sender': src.from, 'file': src.file_name,\n  'supplier': '', 'invoice_number': '', 'invoice_date': '', 'billed_to': '', 'subtotal': null, 'gst': null, 'qst': null, 'total': null,\n  'currency': '', 'supplier_gst_number': '', 'supplier_qst_number': '',\n  'status': \"REVIEW\", 'review_reasons': \"PDF has no text (scan or image): check by hand\",\n  'email_link': 'https://mail.google.com/mail/u/0/#all/' + src.email_id,\n} };"
      }
    },
    {
      "id": "39ccea7f-3b75-5ad7-8277-8cb3f90c8130",
      "name": "Add row to Google Sheets",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.5,
      "position": [
        1100,
        100
      ],
      "parameters": {
        "operation": "append",
        "documentId": {
          "__rl": true,
          "mode": "url",
          "value": "PASTE_YOUR_GOOGLE_SHEET_URL_HERE"
        },
        "sheetName": {
          "__rl": true,
          "mode": "name",
          "value": "Invoices"
        },
        "columns": {
          "mappingMode": "autoMapInputData",
          "value": {},
          "matchingColumns": [],
          "schema": []
        },
        "options": {}
      }
    },
    {
      "id": "99f16e81-a828-50b5-aa2f-2f86290ff28a",
      "name": "Gmail: label as processed",
      "type": "n8n-nodes-base.gmail",
      "typeVersion": 2.1,
      "position": [
        1320,
        100
      ],
      "parameters": {
        "operation": "addLabels",
        "messageId": "={{ $('Split PDFs').item.json.email_id }}",
        "labelIds": [
          "PICK_THE_LABEL_invoices-processed"
        ]
      }
    }
  ],
  "connections": {
    "Gmail: emails with a PDF invoice": {
      "main": [
        [
          {
            "node": "Split PDFs",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Split PDFs": {
      "main": [
        [
          {
            "node": "Read PDF text",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read PDF text": {
      "main": [
        [
          {
            "node": "Does the PDF have text?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Does the PDF have text?": {
      "main": [
        [
          {
            "node": "AI: extract invoice data",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Scanned PDF: flag for review",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "OpenAI model": {
      "ai_languageModel": [
        [
          {
            "node": "AI: extract invoice data",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Output format": {
      "ai_outputParser": [
        [
          {
            "node": "AI: extract invoice data",
            "type": "ai_outputParser",
            "index": 0
          }
        ]
      ]
    },
    "AI: extract invoice data": {
      "main": [
        [
          {
            "node": "Check amounts and GST/QST numbers",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Check amounts and GST/QST numbers": {
      "main": [
        [
          {
            "node": "Add row to Google Sheets",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Scanned PDF: flag for review": {
      "main": [
        [
          {
            "node": "Add row to Google Sheets",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Add row to Google Sheets": {
      "main": [
        [
          {
            "node": "Gmail: label as processed",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "pinData": {},
  "active": false,
  "settings": {
    "executionOrder": "v1"
  },
  "meta": {
    "templateCredsSetupCompleted": false
  },
  "tags": []
}