{
  "name": "Completeness check (double-entry for automation) v1.1",
  "nodes": [
    {
      "id": "5a70187c-ab1f-4ba9-9b0b-3e3e77520d0d",
      "name": "Every Hour",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.4,
      "position": [
        0,
        0
      ],
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "hours",
              "hoursInterval": 1
            }
          ]
        }
      }
    },
    {
      "id": "177a2f0d-29c3-4c66-90ca-6734340c1418",
      "name": "Settings",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        224,
        0
      ],
      "parameters": {
        "mode": "manual",
        "includeOtherFields": false,
        "assignments": {
          "assignments": [
            {
              "id": "s-label",
              "name": "gmailLabel",
              "value": "invoices",
              "type": "string"
            },
            {
              "id": "s-lookback",
              "name": "lookbackHours",
              "value": "={{ $('Every Monday').isExecuted ? 168 : 48 }}",
              "type": "number"
            },
            {
              "id": "s-grace",
              "name": "graceMinutes",
              "value": 30,
              "type": "number"
            },
            {
              "id": "s-idcol",
              "name": "idColumn",
              "value": "message_id",
              "type": "string"
            },
            {
              "id": "s-alert",
              "name": "alertTo",
              "value": "you@example.com",
              "type": "string"
            }
          ]
        }
      }
    },
    {
      "id": "3b901c29-0c10-45de-af98-101cfdfa406a",
      "name": "Read Source Emails",
      "type": "n8n-nodes-base.gmail",
      "typeVersion": 2.2,
      "position": [
        448,
        0
      ],
      "parameters": {
        "resource": "message",
        "operation": "getAll",
        "returnAll": true,
        "simple": true,
        "filters": {
          "q": "=label:{{ $json.gmailLabel }}",
          "readStatus": "both",
          "receivedAfter": "={{ $now.minus({ hours: $json.lookbackHours }).toISO() }}"
        }
      },
      "alwaysOutputData": true
    },
    {
      "id": "471ac83d-e6ab-4285-a3d3-1608f5b6c898",
      "name": "Read Logged Rows",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        672,
        0
      ],
      "parameters": {
        "resource": "sheet",
        "operation": "read",
        "documentId": {
          "__rl": true,
          "mode": "list",
          "value": "",
          "cachedResultName": "Your log sheet"
        },
        "sheetName": {
          "__rl": true,
          "mode": "list",
          "value": "",
          "cachedResultName": "Sheet1"
        }
      },
      "executeOnce": true,
      "alwaysOutputData": true
    },
    {
      "id": "95037964-da0f-443d-a520-f8724eb6ed94",
      "name": "Balance the Books",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        896,
        0
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "language": "javaScript",
        "jsCode": "const s = $('Settings').first().json;\nconst isStatement = $('Every Monday').isExecuted;\nconst graceCutoff = Date.now() - Number(s.graceMinutes) * 60000;\nconst source = $('Read Source Emails').all().map(i => i.json).filter(m => m.id);\nconst rows = $input.all().map(i => i.json);\n\nconst counts = {};\nfor (const r of rows) {\n  const id = String(r[s.idColumn] ?? '').trim();\n  if (id) counts[id] = (counts[id] || 0) + 1;\n}\n\nconst missing = [];\nlet waiting = 0;\nlet accounted = 0;\nfor (const m of source) {\n  if (counts[m.id]) { accounted++; continue; }\n  if (Number(m.internalDate) >= graceCutoff) { waiting++; continue; }\n  missing.push({ id: m.id, subject: m.Subject || '(no subject)', from: m.From || '', received: new Date(Number(m.internalDate)).toISOString() });\n}\nconst sourceIds = new Set(source.map(m => m.id));\nconst duplicates = Object.entries(counts).filter(([id, n]) => n > 1 && sourceIds.has(id)).map(([id, n]) => ({ id, rows: n }));\nconst balanced = missing.length === 0 && duplicates.length === 0;\n\nconst esc = t => String(t).replace(/[&<>]/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;' }[c]));\nlet html = '<p><b>' + source.length + ' in, ' + accounted + ' accounted for, ' + missing.length + ' missing, ' + duplicates.length + ' duplicated, ' + waiting + ' still inside the ' + s.graceMinutes + '-minute grace period.</b></p>';\nif (missing.length) html += '<p>Missing from the sheet:</p><ul>' + missing.map(m => '<li>' + esc(m.received) + ' | ' + esc(m.from) + ' | ' + esc(m.subject) + ' | id ' + esc(m.id) + '</li>').join('') + '</ul>';\nif (duplicates.length) html += '<p>Logged more than once:</p><ul>' + duplicates.map(d => '<li>id ' + esc(d.id) + ' appears ' + d.rows + ' times</li>').join('') + '</ul>';\n\nif (isStatement) html += '<p>This statement goes out every Monday, even when everything balances. If it stops arriving, the check itself has stopped.</p>';\n\nconst subject = balanced\n  ? 'Weekly statement: ' + source.length + ' in, ' + accounted + ' accounted for, 0 open'\n  : 'Books do not balance: ' + missing.length + ' missing, ' + duplicates.length + ' duplicated (label ' + s.gmailLabel + ')';\n\nreturn [{ json: { balanced, send: !balanced || isStatement, inCount: source.length, accounted, missingCount: missing.length, duplicateCount: duplicates.length, waiting, missing, duplicates, alertTo: s.alertTo, alertSubject: subject, alertHtml: html } }];"
      }
    },
    {
      "id": "ab101f9a-b717-45a9-bd0c-a36b3ae69300",
      "name": "Anything to say?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        1120,
        0
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict"
          },
          "conditions": [
            {
              "leftValue": "={{ $json.send }}",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        }
      }
    },
    {
      "id": "2fd16cc5-b89c-40ed-9173-9c701352e4f6",
      "name": "Email a person",
      "type": "n8n-nodes-base.gmail",
      "typeVersion": 2.2,
      "position": [
        1344,
        0
      ],
      "parameters": {
        "resource": "message",
        "operation": "send",
        "sendTo": "={{ $json.alertTo }}",
        "subject": "={{ $json.alertSubject }}",
        "emailType": "html",
        "message": "={{ $json.alertHtml }}",
        "options": {
          "appendAttribution": false
        }
      }
    },
    {
      "id": "f7ac6a5f-7acc-4b64-960d-9fe323ff1fcb",
      "name": "How it works",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -40,
        -520
      ],
      "parameters": {
        "content": "## Completeness check (double-entry for automation)\n\nYour automation says it worked. This checks.\n\n**Left side:** every email in a Gmail label (the source).\n**Right side:** every row in the sheet your automation writes to (the outcome).\n\nEvery email must appear **exactly once** in the sheet. If one is missing (after the grace period) or logged twice, you get one email. Every Monday it also sends a short statement, even when everything balances. If Monday's email does not come, the check itself has stopped.\n\n**Setup (5 minutes)**\n1. In your existing automation, write the Gmail message ID into a column called `message_id` (in n8n: `{{ $json.id }}` from the Gmail trigger).\n2. Open **Settings**: your label, how far back to look, grace minutes, alert address.\n3. Connect Gmail and Google Sheets, pick your sheet in **Read Logged Rows**.\n4. Activate.\n\nWorks whatever writes the rows: an n8n workflow, Zapier, Make, an AI agent or a person.\n\nBy StanAutomate\n\n**Limits:** it reads one sheet tab, so anything your automation sends to another tab, such as a needs-a-person list, shows as missing. It checks that each email arrived once, not that the row is right. For the first two days, emails handled before you added the column show as missing.",
        "color": 4,
        "width": 620,
        "height": 480
      }
    },
    {
      "id": "monday-trigger",
      "name": "Every Monday",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.4,
      "position": [
        0,
        200
      ],
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "weeks",
              "weeksInterval": 1,
              "triggerAtDay": [
                1
              ],
              "triggerAtHour": 7
            }
          ]
        }
      }
    }
  ],
  "connections": {
    "Every Hour": {
      "main": [
        [
          {
            "node": "Settings",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Settings": {
      "main": [
        [
          {
            "node": "Read Source Emails",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read Source Emails": {
      "main": [
        [
          {
            "node": "Read Logged Rows",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read Logged Rows": {
      "main": [
        [
          {
            "node": "Balance the Books",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Balance the Books": {
      "main": [
        [
          {
            "node": "Anything to say?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Anything to say?": {
      "main": [
        [
          {
            "node": "Email a person",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Every Monday": {
      "main": [
        [
          {
            "node": "Settings",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "settings": {
    "executionOrder": "v1"
  },
  "pinData": {}
}